Chapter 13 Abstract Classes and Interfaces

Similar documents
Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Motivations. Chapter 13 Abstract Classes and Interfaces

Chapter 13 Abstract Classes and Interfaces

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

Chapter 9 Abstract Classes and Interfaces

C20a: Selected Interfaces in Java API

Abstract Classes Interfaces

We are on the GUI fast track path

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Chapter 14 Abstract Classes and Interfaces

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

What is an interface? Why is an interface useful?

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

CS171:Introduction to Computer Science II. Li Xiong

Abstract Classes and Interfaces

Object Oriented System Development Paradigm. Sunnie Chung CIS433 System Analysis Methods

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Introduction to Programming Using Java (98-388)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CS1150 Principles of Computer Science Objects and Classes

CS-202 Introduction to Object Oriented Programming

Java Object Oriented Design. CSC207 Fall 2014

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

ITI Introduction to Computing II

Abstract Classes and Interfaces. CSE 114, Computer Science 1 Stony Brook University

Inheritance and Interfaces

ITI Introduction to Computing II

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Programming Exercise 14: Inheritance and Polymorphism

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Cloning Enums. Cloning and Enums BIU OOP

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Inheritance and Polymorphism

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Programming overview

Inheritance and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST II

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Chapter 4 Defining Classes I

Tecniche di Progettazione: Design Patterns

More on Objects in JAVA TM

Programming II (CS300)

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

The static keyword Used to denote fields and methods that belong to a class (but not to any particular object).

For this section, we will implement a class with only non-static features, that represents a rectangle

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Inheritance, Polymorphism, and Interfaces

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Programming II (CS300)

Introduction to Inheritance

Inheritance (continued) Inheritance

Java Fundamentals (II)

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Chapter 6 Introduction to Defining Classes

COP 3330 Final Exam Review

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Index COPYRIGHTED MATERIAL

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

25. Generic Programming

Interfaces. James Brucker

CSCE3193: Programming Paradigms

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

15CS45 : OBJECT ORIENTED CONCEPTS

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CH. 2 OBJECT-ORIENTED PROGRAMMING

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Computer Science II (20073) Week 1: Review and Inheritance

Another IS-A Relationship

Lecture Notes Chapter #9_b Inheritance & Polymorphism

INHERITANCE. Spring 2019

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

INTERFACE WHY INTERFACE

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

CMSC 132: Object-Oriented Programming II

Software and Programming 1

Chapter 6: Inheritance

CISC370: Inheritance

Principles of Object Oriented Programming. Lecture 4

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Transcription:

Chapter 13 Abstract Classes and Interfaces 1

Abstract Classes Abstraction is to extract common behaviors/properties into a higher level in the class hierarch so that they are shared (implemented) by subclasses as needed. An abstract class may contain abstract methods (methods with no implementation) so that subclasses can implement these methods to meet their difference needs (behaviors). A concrete subclass that extends an abstract class MUST implement all inherited abstract methods, even if they are not used in the subclass. 2

Example: 3

Abstract Class Notes An abstract class cannot be instantiated using the new operator. An abstract class can define constructors (protected visibility), which are invoked in the constructors of its subclasses. An abstract class may contain concrete methods. A subclass can be abstract even if its superclass is concrete (e.g., class Object is concrete!). A subclass can override a method from its superclass to define it abstract. In this case, the subclass MUST be defined abstract. An abstract class can be used as a data type. For example, creating an array of the abstract class GeometricObjects: GeometricObject[] geo = new GeometricObject[10]; 4

Example: Date and Calendar Classes An instance of java.util.date represents a specific instant in time with millisecond precision. java.util.calendar is an abstract base class for extracting information such as year, month, date, hour, minute and second from a Date object. Subclasses of Calendar can implement specific calendar systems such as Gregorian calendar, Lunar Calendar, and Jewish calendar. The Gregorian calendar in implemented in Java (java.util.gregoriancalendar). 5

The get() Method in Class Calendar Method get(int field) defined in class Calendar is useful to extract the date and time information from a Calendar object. The fields are defined as constants, as shown in the following. 6

Gregorian Calendar Subclass Currently, java.util.gregoriancalendar for the Gregorian calendar is supported in the Java API. You can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and use new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0-based, i.e., 0 is for January. HW: Type, compile, and run program TestCalendar, page 504, Listing 13.6. 7

Abstract Calendar Class and Its GregorianCalendar Subclass 8

Interfaces An interface is similar to an abstract class, it contains only constants and abstract methods. Interfaces specify common behavior for objects, such as specifying whether objects are comparable, edible, cloneable, etc. Abstract classes used with (strong) is-a relationships; while interfaces used with (weak or is-kind-of) is-a relationships. class Townhouse extends House class Townhouse extends House implements AirConditioning class Chicken extends Animal class Chicken extends Animal implements edible 9

Interface Notes A class may implement more than one Interface classes. Interfaces used to accommodate Multiple Inheritance. Interfaces are used when no revision of behavior is needed. An interface is treated like class. Each interface is compiled into a separate bytecode file. Like an abstract class, you cannot create an instance from an interface using the new operator. In interface is used like abstract class, you can use an interface as a data type for a variable, as the result of casting, and so on. 10

Define an Interface To distinguish an interface from a class, Java uses the following syntax to define an interface: public interface InterfaceName { constant declarations; abstract method signatures; Example: public interface Edible { // describe how to eat public abstract String howtoeat(); 11

Example You can use the Edible interface to specify whether an object is edible. This is done by allowing the class of that object implement this interface. For example, the classes Chicken and Fruit implement interface edible (See TestEdible, page 506). 12

Omitting Modifiers in Interfaces All data fields are public final static and all methods are public abstract in an interface. Thus, these modifiers can be omitted, as shown below: public interface T1 { public static final int K = 1; Equivalent public interface T1 { int K = 1; public abstract void p(); void p(); A constant defined in an interface can be accessed using syntax InterfaceName.CONSTANT_NAME (e.g., T1.K). 13

Interface Comparable // This interface is defined in java.lang package java.lang; public interface Comparable<E> { public int compareto(e o); Note: Since all the numeric wrapper classes (Double, Float, Long, Integer, Short, Byte, BigInteger, BigDecimal) and the Character class implement interface Comparable, the compareto() method is already implemented in these classes. 14

Example: Classes Integer and BigInteger public class Integer extends Number implements Comparable<Integer> { // class body omitted public class BigInteger extends Number implements Comparable<BigInteger> { // class body omitted @Override public int compareto(integer o) { // Implementation omitted @Override public int compareto(biginteger o) { // Implementation omitted Examples: Classes String and Date public class String extends Object implements Comparable<String> { // class body omitted public class Date extends Object implements Comparable<Date> { // class body omitted @Override public int compareto(string o) { // Implementation omitted @Override public int compareto(date o) { // Implementation omitted 15

Import java.util.date;... Code Examples System.out.println(new Integer(3).compareTo(new Integer(5))); //output is -1 System.out.println("ABC".compareTo("ABE")); //output is -2 date1 = new Date(2017, 1, 1); date2 = new Date(2016, 1, 1); System.out.println(date1.compareTo(date2)); //output is 1 Note: The method returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this object is greater than, equal to, or less than the passed object. 16

User-Defined Class to Implement Comparable Note: How you compare 2 objects is a problem-specific. Comparing 2 cars is different than comparing 2 apples, or 2 chairs, or 2 persons, etc. 17

public class ComparableRectangle extends Rectangle implements Comparable<ComparableRectangle> { //Construct a ComparableRectangle with specified properties public ComparableRectangle(double width, double height) { super(width, height); @Override //Implement method compareto() public int compareto(comparablerectangle o) { if (getarea() > o.getarea()) return 1; else if (getarea() < o.getarea()) return -1; else return 0; @Override //Implement method tostring() public String tostring() { return super.tostring() + " Area: " + getarea(); 18

Interface Cloneable It is called Marker Interface, An empty interface. A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements interface Cloneable is marked cloneable, and its objects can be cloned using the clone() method defined in class Object. package java.lang; public interface Cloneable { Note: The cloned object has its own memory space. 19

Code Example Many classes (e.g., Date and Calendar) in the Java library implement Cloneable. Thus, the instances of these classes can be cloned. For example, the following code Calendar calendar = new GregorianCalendar(2003, 2, 1); Calendar calendarcopy = (Calendar)calendar.clone(); System.out.println("calendar == calendarcopy is " + (calendar == calendarcopy)); System.out.println("calendar.equals(calendarCopy) is " + calendar.equals(calendarcopy)); displays calendar == calendarcopy is false calendar.equals(calendarcopy) is true 20

Implementing Interface Cloneable To define a custom class that implements interface Cloneable, the class must override method clone() in class Object. Class House implements Cloneable and Comparable. See partial code next slide. See full code page 515, Listing 13.11. 21

public class House implements Cloneable, Comparable<House> { // variables and methods declaration @Override //Override method clone from class Object public Object clone() { try { return super.clone(); catch (CloneNotSupportedException ex) { return null; @Override //Implement method compareto()from Comparable public int compareto(house o) { if (area > o.area) return 1; else if (area < o.area) return -1; else return 0; 22

Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Shallow Copy (by default) 23

Shallow vs. Deep Copy House house1 = new House(1, 1750.50); House house2 = (House)house1.clone(); Deep Copy (customized) See code next slide. See full code page 514-516. 24

Shallow Copy: @Override //Override method clone from class Object public Object clone() { try { return super.clone(); //shallow copy catch (CloneNotSupportedException ex) { return "Object cannot be cloned!"; Deep Copy: @Override //Override method clone from class Object public Object clone() { try { House houseclone = (House)super.clone();//shallow copy //deep copy on Date object whenbuilt houseclone.whenbuilt = (Date)(whenBuilt.clone()); return houseclone; catch (CloneNotSupportedException ex) { return "Object cannot be cloned!"; 25

Interfaces vs. Abstract Classes In an interface, the data must be constants; an abstract class can have all types of data. Each method in an interface has only a signature without implementation; an abstract class can have concrete methods. 26

Interfaces vs. Abstract Classes If c is an instance of Class2, Then c is also an instance of classes Object, Class1, Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2. 27

Visibility Modifiers - Revisited Each class can present two contracts: - one for the users of the class - one for the extenders (subclasses) of the class Make the data fields private and the accessor methods (getters and setters) public if they are intended for the users of the class. Make the data fields and methods protected if they are intended for extenders (subclasses) of the class. A class should use the private modifier to hide its data from direct access by clients (users). Use get() and set() methods to provide users with access to only private data that you want the user to see and/or modify. 28

Instance vs. Static - Revisited Instance variable means that each object of the class has its own copy of variables. Instance method means that the method is invoked on the objects (objectname.methodname()). Static variable means that all objects share that one variable. Static method means that the method is invoked on the class (classname.methodname()). Note: a static method or variable can be invoked from an instance method, but an instance variable or method cannot be invoked from a static method! 29

Inheritance vs. Aggregation - Revisited Inheritance implements is-a relationship. E.g., Orange is-a Fruit Class Orange inherits from class Fruit Aggregation implements has-a relationship. E.g., Staff has-a Name Class Staff aggregates (uses) class Name 30

Class Design Hints Coherence: A class describes a single entity. All data fields and operations should logically fit together to support that entity. Do not combine entities into one class, we should not combine students and staff in the same class, because they are different. Separating responsibilities: A single entity with too many responsibilities can be broken into several classes. For example, Java defines classes String and StringBuilder to deal with strings. Each has different responsibilities - String deals with immutable strings; while StringBuilder deals with mutable strings. Reuse: Design for reuse. A class should not imposes no restrictions on what or when the user can do with it. Methods should function independently of their order of occurrence. Users should be able to set properties in any order, with any combination of values. 31

Class Design Hints Consistency: Follow Java programming style and naming conventions. Use informative names for classes, variables, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors. Employ Encapsulation and utilize getters and setters as needed. Provide a public no-arg constructor and override methods equals and tostring defined in class Object whenever possible. 32

End of Slides 33