Abstract Classes and Interfaces in Java Reference: COS240 Syllabus

Slides:



Advertisements
Similar presentations
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Advertisements

Chapter 14 Abstract Classes and Interfaces 1. Objectives To design and use abstract classes (§14.2). To process a calendar using the Calendar and GregorianCalendar.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 1 Object-Oriented.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 10 Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 1 Introduction to Computers,
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Polymorphism & Interfaces
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 1 Chapter 13 Abstract Classes and Interfaces.
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 10 Abstract Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Abstract Classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 1 Chapter 13 Abstract Classes and Interfaces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Abstract Classes and Interfaces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Abstract Classes and Interfaces.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Abstract Classes Course Lecture Slides 7 June 2010 “None of the abstract.
1 Inheritance and Subclasses. 2 Inheritance Often we create very similar classes –Different types of triangles: equilateral, isosceles, etc. –Different.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 / 41 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 5 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 11 Abstract Classes.
CS 112 Programming 2 Lecture 10 Abstract Classes & Interfaces (1)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Interfaces Are used to model weak inheritance relationships Object-inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Chapter 15 Abstract Classes and Interfaces.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
1 Chapter 5 Abstract Classes and Interfaces. 2 Objectives u To design and use abstract classes. u To process a calendar using the Calendar and GregorianCalendar.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Object-Oriented Programming (part 4 – Abstract Classes)
Lecture 5:Interfaces and Abstract Classes
Chapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Chapter 11 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
IST311 / 602 Cleveland State University – Prof. Victor Matos
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Chapter 13 Abstract Classes and Interfaces
CIS3023: Programming Fundamentals for CIS Majors II
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Chapter 13 Abstract Classes and Interfaces
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Chapter 12 Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
IST311 / 602 Cleveland State University – Prof. Victor Matos
Chapter 11 Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 13 Abstract Classes and Interfaces Part 01
Presentation transcript:

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

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

Inheritance Review

Polymorphism Review

Interfaces & Abstract Classes Instead of Introduction Look at next slide

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.

Interfaces & Abstract Classes Brief presentation

Interfaces & Abstract Classes The Interface concept

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

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.

Interfaces & Abstract Classes The Abstract Class concept

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

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

Abstract Classes & Interfaces Comprehensive presentation

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

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

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

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

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.

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.

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

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

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

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

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

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

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

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?

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?

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

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

Java predefined abstract classes

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

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

Interfaces

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.

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

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

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

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

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

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

Java supported interfaces

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

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 {

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

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

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

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

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

Java supported interfaces: ActionListener Run the application

Java supported interfaces: Cloneable Run the application

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

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

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