Presentation is loading. Please wait.

Presentation is loading. Please wait.

Abstract Classes and Interfaces in Java Reference: COS240 Syllabus

Similar presentations


Presentation on theme: "Abstract Classes and Interfaces in Java Reference: COS240 Syllabus"— Presentation transcript:

1 Abstract Classes and Interfaces in Java Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 15 Title: Abstract Classes and Interfaces in Java Reference: COS240 Syllabus

2 Lecture Contents: Review on Inheritance and Polymorphism
Abstract Classes Why Abstract Methods? Interfaces Example: the Comparable Interface Interfaces vs. Abstract Classes

3 Inheritance Review

4 Polymorphism Review

5 Interfaces & Abstract Classes
Instead of Introduction Look at next slide

6 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.

7 Interfaces & Abstract Classes
Brief presentation

8 Interfaces & Abstract Classes
The Interface concept

9 No method bodies – just method header.
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 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

10 This is a “back door” approach to multiple inheritance
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.

11 Interfaces & Abstract Classes
The Abstract Class concept

12 A class where some methods are unspecified (like in an interface).
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. An abstract class can implement an interface but not implement all of its methods, in which case a class that extends the abstract class must finish the specification from the interface. 12

13 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 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 13

14 Abstract Classes & Interfaces
Comprehensive presentation

15 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

16 GeometricObject – Circle, Rectangle
GeometricObject ↑ ↑ Circle Rectangle Common properties for both Circle and Rect: Color, filled/nofilled, dateCreated Circle – specific property: radius Rectangle – specific properties: width, height

17 GeometricObject – Circle, Rectangle
↑ ↑ Circle Rectangle Common properties for both Circle and Rect: Color, filled/nofilled, dateCreated Circle – specific behavior: getArea(), getPerimeter() Rectangle – specific behavior:

18 GeometricObject – Circle, Rectangle
↑ ↑ 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()

19 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.

20 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.

21 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

22 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

23 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

24 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() ); } }

25 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).

26 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(); }

27 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

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(geo1,o[i])); Q.: Can you guess/predict the expected output?

29 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?

30 Inheritance, polymorphism and abstract classes
Expected output: Geo1 Geo2 ======================= false false false true

31 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

32 Java predefined abstract classes

33 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

34 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

35 Interfaces

36 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.

37 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

38 Interface example Given: Edible interface and two separate independent inheritance hierarchies: =================================================================================================== Animal Fruit(Edible) ↑ ↑ ↑ ↑ Tiger Chicken(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

39 Open files Edible.java & ProgInterfaceEdible.java
Task: using Edible interface to specify which object is edible, in other words has implemented method howToEat(). Browse the source text

40 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()

41 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

42 Open files Edible.java & ProgInterfaceEdible.java
Run the application

43 Java supported interfaces

44 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); {

45 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 {

46 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

47 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

48 User Defined class implement interfaces: Comparable
Solution scheme for the second option: GeometricObject Rectangle Comparable ↑ ↑ ComparableRectangle

49 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) {…} }

50 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));

51 Java supported interfaces: ActionListener
Run the application

52 Java supported interfaces: Cloneable
Run the application

53 Conclusion Abstract class contain
regular methods and abstract methods and polymorphic approach is within one only specific inheritance hierarchy. GeometricObject, Circe, Rectangle

54 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

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


Download ppt "Abstract Classes and Interfaces in Java Reference: COS240 Syllabus"

Similar presentations


Ads by Google