Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"— Presentation transcript:

1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG, COS dept Lecture 15 Title: Abstract Classes and Interfaces in Java Reference: COS240 Syllabus

2 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Lecture Contents: F Review oh Inheritance and Polymorphism F Abstract Classes F Why Abstract Methods? F Interfaces F Example: the Comparable Interface F Interfaces vs. Abstract Classes

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Inheritance F Review

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Polymorphism F Review

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Interfaces & Abstract Classes F Brief presentation

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 Interfaces & Abstract Classes The Interface concept

7 7 Interface 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 } 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); }

8 8 public class BusDriver extends Person implements Driver { // must include implementation for each of the three methods from Driver } May also have This is a “back door” approach to multiple inheritance for Java via extends and implements. Single inheritance via extends and extra inheritance via implements.

9 9 Interfaces & Abstract Classes The Abstract Class concept

10 10 Abstract Classes 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. Similar for C#

11 11 Abstract Class Example abstract class CacheFile { String filename; byte[] contents; void flush() { // Write file to disk } void refresh() { // Load file from disk } abstract String deserialize(); abstract byte[] serialize(String s); } These methods are defined These methods are abstract because how you want to store data into the file is application-dependent May have defined methods and abstract methods.

12 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 12 Abstract Classes & Interfaces F Comprehensive presentation

13 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 13 Inheritance hierarchy F If you move from super class down to sub class, classes become more specific and more concrete. F If you move from sub class up to super class, classes become more general and less specific F Sometimes super class is so abstract that it cannot have any specific instances. F Such a class is referred to as an ABSTRACT CLASS

14 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 GeometricObject – Circle, Rectangle Object ↑ GeometricObject ↑ Circle Rectangle F Common properties: –Color, filled/nofilled, dateCreated F Circle – specific properties: radius F Rectangle – specific properties: width, height

15 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 GeometricObject – Circle, Rectangle GeometricObject ↑ Circle Rectangle F Common properties: –Color, filled/nofilled, dateCreated F Circle – specific properties and behavior: –Radius, getArea(), getPerimeter() F Rectangle – specific properties and behavior: –width, height, getArea(), getPerimeter()

16 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Inheritance hierarchy F Is it reasonable to generalize getArea(), getPerimeter() methods? F 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. F 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.

17 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Open file ProgGeometricObjectAbstractClass.java abstract class GeometricObject { … public abstract double getArea(); public abstract double getPerimeter(); } F You cannot create instances of abstract classes using new operator. F Constructors in abstract classes are protected because they are used only by subclasses. F 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.

18 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 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 method return "CircleCircle:\n" + super.toString(); } }

19 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 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 method return "RectangleRectangle:\n" + super.toString(); } }

20 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Open file ProgGeometricObjectAbstractClass.java F Why do we need abstract methods? What benefits if any? F 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

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 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() ); } }

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 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: F 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).

23 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 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(); }

24 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 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("The perimeter is " + o.getPerimeter() ); }

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 Inheritance, polymorphism and abstract classes F 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])); F Q.: Can you analyze the expected output?

26 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Inheritance, polymorphism and abstract classes F 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])); F Q.: Can you analyze the expected output?

27 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Inheritance, polymorphism and abstract classes F Expected output: –Geo1Geo2 –======================= – false false – false true – false false

28 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 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. F BUT: such a solution should lose the advantages provided when using polymorphism

29 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 Java predefined abstract classes

30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 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

31 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Open file ProgCalendar.java F Comments: F 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

32 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Interfaces

33 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Interfaces F Interface is class-like construct that contains only constants and abstract methods. F Interface is similar to abstract class, but its intent is to specify common behavior for objects that belong even to different inheritance hierarchies. F Reminder: Abstract class contain regular methods and abstract methods and polymorphic approach is within one only specific inheritance hierarchy.

34 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Interfaces  To distinguish an interface from a class, Java uses interface reserved word: public interface Edible { public abstract String howToEat(); } F Each interface to be saved in separate file like Edible.java. F You cannot create an instance of interface with new F You can use interface as data type for ref var, or as a result of casting

35 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Interface example  Given: Edible interface and two separate independent inheritance hierarchies: =================================================================================================== Animal Fruit(Edible) ↑↑ ↑↑ Tiger Chicken(Edible) AppleOrange =================================================================================================== F Animal – regular base class F Fruit – base class implements Edible interface F Chicken – child class implements Edible interface F Tiger – regular child class F Apple, Orange – regular child classes

36 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 Open files Edible.java & ProgInterfaceEdible.java  Task: using Edible interface to specify which object is edible, in other words has implemented method howToEat(). F Browse the source text

37 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 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()

38 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 Open files Edible.java & ProgInterfaceEdible.java  Fruit implements Edible, and does not implement howToEat() method. F 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

39 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Open files Edible.java & ProgInterfaceEdible.java F Run the application

40 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Java supported interfaces

41 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Java supported interfaces: Comparable F Problem: we need a method to return the larger of two objects of the same type: F Two students, two dates, two circles, two rectangles F It is must the two objects to be comparable F Comparability is considered a common behavior F Java provides Comparable interface for this purpose package java.lang; public interface Comparable { public int compareTo(Object o); {

42 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 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 }

43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Java supported interfaces: Comparable  Given String s;Date d; //------------------------------- (s instanceof String) istrue (s instanceof Object) istrue (s instanceof Comparable) is true //------------------------------- (d instanceof Date) istrue (d instanceof Object) istrue (d instanceof Comparable) is true

44 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 User Defined class implement interfaces: Comparable F Reminder : class Rectangle F We cannot compare instances of Rectangle, because Rectangle does not implement Comparable interface F How to proceed? –Re edit Rectangle class to implement Comparable OR –Create new class ComparableRectangle to extend Rectangle and to implement Comparable

45 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 User Defined class implement interfaces: Comparable F Solution scheme for the second option: GeometricObject ↑ Rectangle Comparable ↑ ↑ ComparableRectangle - - - - -

46 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 User Defined class implement interfaces: Comparable F Open source file ProgComparableRectangle.java F Source text skeleton for ComparableRectangle public class ComparableRectangle extends Rectangle implements Comparable { public ComparableRectangle(…) { …} public compareTo(Object o) {…} }

47 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 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));

48 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 Java supported interfaces: ActionListener F Run the application

49 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 013213080749 Thank You for Your attention!


Download ppt "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"

Similar presentations


Ads by Google