Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COS240 O-O Languages AUBG, COS dept Lecture 15 Title: Abstract Classes and Interfaces in Java Reference: COS240 Syllabus Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Lecture Contents: Review on Inheritance and Polymorphism Abstract Classes Why Abstract Methods? Interfaces Example: the Comparable Interface Example: the Comparable Interface Interfaces vs. Abstract Classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Inheritance Review Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Polymorphism Review Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Interfaces & Abstract Classes Instead of Introduction Look at next slide Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Interfaces & Abstract Classes A Super class defines common behavior for related subclasses. An interface can be used to define common behavior for classes, incl. unrelated classes An abstract class cannot be used to create objects. An abstract class can contain abstract methods, which are implemented in concrete subclasses. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 Interfaces & Abstract Classes Brief presentation Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 7 Interfaces & Abstract Classes The Interface concept Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 8 Interface No method bodies – just method header. Must provide implementation when used. public interface Driver { void turnWheel(double angle); void pressAccelerator(double amount); void pressBrake(double amount); } public class BusDriver implements Driver { // must include implementation for each of the three methods from Driver } 9 May also have public class BusDriver extends Person implements Driver { // must include implementation for each of the three methods from Driver } This is a “back door” approach to multiple inheritance for Java via extends and implements. Single inheritance via extends and extra inheritance via implements. 10 Interfaces & Abstract Classes The Abstract Class concept Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 11 Abstract Classes Similar for C# • A class where some methods are unspecified (like in an interface). – The unspecified methods are declared abstract. – The class also is declared abstract. • An abstract class must be sub-classed (i.e. extended) - you cannot instantiate objects of an abstract type. • Useful if you want to specify an “interface” along with some default behaviors. 12 Abstract Class Example May have defined methods and abstract methods. abstract class CacheFile { String filename; byte[] contents; void flush() { // Write file to disk } void refresh() { // Load file from disk } } These methods are defined These methods are abstract abstract String deserialize(); because how you want abstract byte[] serialize(String s); to store data into the file is application-dependent 13 Abstract Classes & Interfaces Comprehensive presentation Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Inheritance hierarchy If you move from super class down to sub class, classes become more specific and more concrete. If you move from sub class up to super class, classes become more general and less specific Sometimes super class is so abstract that it cannot have any specific instances. Such a class is referred to as an ABSTRACT CLASS Cn Cn-1 ..... C2 C1 Since o is an instance of C1, o is also an Object instance of C C …, C , and Cn 2, 3,Education,n-1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Inc. All rights reserved. 0132130807 15 GeometricObject – Circle, Rectangle Object ↑ GeometricObject ↑ ↑ Circle Rectangle Common properties for both Circle and Rect: – Color, filled/nofilled, dateCreated – specific property: radius Rectangle – specific properties: width, height Circle Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 GeometricObject – Circle, Rectangle GeometricObject ↑ ↑ Circle Rectangle Common properties for both Circle and Rect: – Color, filled/nofilled, dateCreated Circle – specific behavior: – getArea(), getPerimeter() Rectangle – specific behavior: – getArea(), getPerimeter() Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 GeometricObject – Circle, Rectangle GeometricObject ↑ ↑ Circle Rectangle Common properties for both Circle and Rect: – Color, filled/nofilled, dateCreated Circle – specific property and behavior: – Radius, getArea(), getPerimeter() Rectangle – specific properties and behavior: – width, height, getArea(), getPerimeter() Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 Inheritance hierarchy Is it reasonable to generalize getArea(), getPerimeter() methods? From one side: Since we can compute area and perimeter for all geometric objects, it is better to define getArea(), getPerimeter() as methods in super class GeometricObject. From other side: Both methods cannot be implemented in the base class because their implementation depends on specific properties (radius or height/width) of the geometric object defined in the sub classes. Such methods are referred to as abstract methods and are denoted in the super class using modifier abstract. Class with abstract methods becomes an abstract class and is must to be also denoted abstract. See next slide. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Open file ProgGeometricObjectAbstractClass.java abstract class GeometricObject { … public abstract double getArea(); public abstract double getPerimeter(); } You cannot create instances of abstract classes using new operator. Constructors in abstract classes are protected because they are used only by subclasses. Super class defines common features (incl. methods getArea() and getPerimeter()). Because you don’t know how to compute area and perimeter of geometric objects, both methods are defined as abstract methods. These methods are implemented/overridden in the subclasses. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Open file ProgGeometricObjectAbstractClass.java class Circle extends GeometricObject { … public double getArea() { return Math.PI * radius * radius; } public double getPerimeter() { return 2 * Math.PI * radius; } public String toString()//overridden m. {return "Circle:\n"+super.toString();} } // end of class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Open file ProgGeometricObjectAbstractClass.java class Rectangle extends GeometricObject { … public double getArea() { return width * height; } public double getPerimeter() { return 2 * (width + height); } public String toString(){//overridden m. {return "RecRec:\n"+super.toString();} } // end of class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Open file ProgGeometricObjectAbstractClass.java Why do we need abstract methods? What benefits if any? Browse the main() method: – It creates two geometric objects – circle, rectangle – Invokes equalArea() method – have a careful look at the formal parameters type – Invokes displayGeometricObject() method – have a careful look at the formal parameter type Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 Open file ProgGeometricObjectAbstractClass.java public class ProgGeometricObjectAbstractClass { public static void main(String args[]) { GeometricObject geo1 = new Circle(5.); GeometricObject geo2 = new Rectangle(5., 3.); System.out.println("The two object have same area? "+ equalArea(geo1, geo2) ); displayGeometricObject(geo1); displayGeometricObject(geo2); } // end of main public static boolean equalArea( GeometricObject o1, GeometricObject o2) { return o1.getArea() == o2.getArea(); } public static void displayGeometricObject(GeometricObject o) { System.out.println("The area is " + o.getArea() ); System.out.println("The perimeter is " + o.getPerimeter() ); } } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 Open file ProgGeometricObjectAbstractClass.java Thanks to declaring abstract methods in super class, it is valid to create a connection btw super class and sub classes through getArea()/getPerimeter() methods and apply the polymorphic approach or in other words: Reference variable of a super class type (formal parameter) can point to an object of its sub class type (actual argument – look at its actual type). Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 Open file ProgGeometricObjectAbstractClass.java Equalarea() method to have two parameters GeometricObject and to compare to equality the area of a circle and the area of a rectangle. public static boolean equalArea(GeometricObject o1, GeometricObject o2) { return o1.getArea() == o2.getArea(); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Open file ProgGeometricObjectAbstractClass.java displayGeometricObject() method to have a parameter GeometricObject and to display: – the area and perimeter of a circle or – the area and perimeter of a rectangle (depends on actual argument) when method called. public static void displayGeometricObject(GeometricObject o) { System.out.println("The area is " + o.getArea() ); System.out.println(“Perimeter is "+o.getPerimeter()); } // end of method Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Inheritance, polymorphism and abstract classes Given the source: GeometricObject geo1 = new Circle(5.); GeometricObject geo2 = new Rectangle(5., 3.); GeometricObject[] o = { new Circle(2.), new Circle(3.), new Rectangle(5., 3.), new Rectangle(4.,6.) }; for (int i=0; i< o.length; i++) System.out.println("The two objects have same area?"+ equalArea(geo1,o[i])); Q.: Can you guess/predict the expected output? Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Inheritance, polymorphism and abstract classes Given the source: GeometricObject geo1 = new Circle(5.); GeometricObject geo2 = new Rectangle(5., 3.); GeometricObject[] o = { new Circle(2.), new Circle(3.), new Rectangle(5., 3.), new Rectangle(4.,6.) }; for (int i=0; i< o.length; i++) System.out.println("The two objects have same area?"+ equalArea(geo2,o[i])); Q.: Can you guess/predict the expected output? Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 Inheritance, polymorphism and abstract classes Expected – – – – – – output: Geo1 Geo2 ======================= false false false false false true false false Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 Digression on equalArea() problem The task to compare the area of a circle and the area of a rectangle could be solved without specifying abstract class GeometricObject and erasing the getArea()/getPerimeter() methods from the super class. BUT: such a solution should lose the advantages provided when using polymorphism Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Java predefined abstract classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Java library: Calendar - GregorianCalendar java.util.Calendar is an abstract base class for extracting detailed calendar info: y, m, d, h, m, s Subclasses of Calendar can implement specific calendar systems: – Gregorian calendar, – Lunar calendar, – Jewish calendar Java supports subclass java.util.GregorianCalendar Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Open file ProgCalendar.java Comments: Calendar cl1 = new GregorianCalendar(); – cl1 declared type is Calendar – cl1 actual type is GregorianCalendar – Polymorphism in action: in other words a ref var of a super class type can point to an object of its sub class type. Task: Modify the ProgCalendar.java source file with String dayNameOfWeek(int dayOfWeek) method to return strings “Sunday”, “Monday”, … “Saturday” depending on calling integer argument value 1, 2, ...7 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Interfaces Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Interfaces Interface is class-like construct that contains only constants and abstract methods. Interface is similar to abstract class, but its intent is to specify common behavior for objects that belong even to different inheritance hierarchies. Reminder1: Abstract class contain regular methods and abstract methods and polymorphic approach is within one only specific inheritance hierarchy. Reminder 2: the instead of introduction slide 6. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 Interfaces To distinguish an interface from a class, Java uses interface reserved word: public interface Edible { public abstract String howToEat(); } Each interface to save in separate file like Edible.java. You cannot create an instance of interface with new You can use interface as data type for ref var, or as a result of casting Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 Interface example Given: Edible interface and two separate independent inheritance hierarchies: =================================================================================================== Animal ↑ ↑ Tiger Chicken(Edible) Fruit(Edible) ↑ ↑ Apple Orange =================================================================================================== Animal – regular base class Fruit – base class implements Edible interface Chicken – child class implements Edible interface Tiger – regular child class Apple, Orange – regular child classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 Open files Edible.java & ProgInterfaceEdible.java using Edible interface to specify which object is edible, in other words has implemented method howToEat(). Task: Browse the source text Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Open files Edible.java & ProgInterfaceEdible.java Chicken extends Animal, implements Edible to specify that chickens are edible, implements method howToEat() Tiger extends Animal, does not implement Edible i.e. tigers are not edible, no need to implement method howToEat() Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Open files Edible.java & ProgInterfaceEdible.java Fruit implements Edible, and does not implement howToEat() method. Therefore Fruit is to be modified as abstract class and concrete subclasses of Fruit must implement howToEat() method, as it is done with Apple class and Orange class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Open files Edible.java & ProgInterfaceEdible.java Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 Java supported interfaces Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Java supported interfaces: Comparable Problem: we need a method to return the larger of two objects of the same type: Two students, Two dates, Two circles, Two rectangles It is must the two objects to be comparable Comparability is considered a common behavior Java provides Comparable interface for this purpose package java.lang; public interface Comparable { public int compareTo(Object o); { Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 Java supported interfaces: Comparable Many Java predefined classes (String, Date) implement Comparable interface to define an order for the objects. String, Date classes provide compareTo() method. Their definition is like this: //------------------------------------public class String extends Object implements Comparable { // class body } //------------------------------------Public class Date extends Object implements Comparable { // class body } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Java supported interfaces: Comparable Given String s; Date d; //------------------------------(s instanceof String) is true (s instanceof Object) is true (s instanceof Comparable) is true //------------------------------(d instanceof Date) is true (d instanceof Object) is true (d instanceof Comparable) is true Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 User Defined class implement interfaces: Comparable Reminder : class Rectangle We cannot compare instances of Rectangle, because Rectangle does not implement Comparable interface How to proceed? – Re edit Rectangle class to implement Comparable OR – Create new class ComparableRectangle to extend Rectangle and to implement Comparable Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 User Defined class implement interfaces: Comparable Solution scheme for the second option: GeometricObject ↑ Rectangle Comparable ↑ ↑ ComparableRectangle - - - - - Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 User Defined class implement interfaces: Comparable Open source file ProgComparableRectangle.java Source text skeleton for ComparableRectangle public class ComparableRectangle extends Rectangle implements Comparable { public ComparableRectangle(…) { …} public int compareTo(Object o) {…} } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49 User Defined class implement interfaces: Comparable How to use the compareTo() method ComparableRectangle r1 = new ComparableRectangle(4.,5.); ComparableRectangle r2 = new ComparableRectangle(4.,6.); ComparableRectangle r3 = new ComparableRectangle(5.,4.); System.out.println(r1.compareTo(r2)); System.out.println(r1.compareTo(r3)); System.out.println(r2.compareTo(r1)); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50 Java supported interfaces: ActionListener Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51 Java supported interfaces: Cloneable Run the application Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 Conclusion Abstract class contain – regular methods and – abstract methods and polymorphic approach is within one only specific inheritance hierarchy. GeometricObject, Circe, Rectangle Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Conclusion Interface contains only abstract methods. Interface is similar to abstract class, but its intent is to specify common behavior for objects that belong even to different inheritance hierarchies Animal, Tiger, Chicken (Edible interface) Fruit (Edible interface), Apple, Orange Interface is a back door to implement multiple inheritance in Java Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Thank You for Your attention! Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55