Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse.

Similar presentations


Presentation on theme: "Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse."— Presentation transcript:

1 Chapter 11 Polymorphism

2 Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse 4. The instanceof Operator II. Abstract Classes and Abstract Methods III. Interfaces 1.Interfaces 2. Fields in Interfaces 3. Implementing Multiple Interfaces 4.Polymorphism and Interfaces

3 I.1 Polymorphism A superclass reference variable can reference objects of a subclass. GradedActivity exam; exam = new GradedActivity(); exam = new FinalExam(50, 7); Polymorphism: The ability to take many forms In Java, a reference variable is polymorphic because it can reference objects of Its own type Types that are subclasses of its type.

4 I.1 Polymorphism Although a GradedActivity variable can reference objects of any subclass of GradedActivity, there is a limit to what the variable can do with thoses objects. GradedActivity exam; exam = new FinalExam(50, 7); The exam variable only knows about methods in the GradedActivity class.

5 I.1 Polymorphism GradedActivity exam; exam = new FinalExam(50, 7); The GradedActivity variable exam can be used to call only three methods of the GradedActivity class: setScore, getScore, getGrade exam.setScore(10); //OK … exam.getScore(); //OK … exam.getGrade(); //OK … exam.getPointsEach(); //Error … exam.getNumMissed(); //Error

6 I.2 Polymorphism and Dynamic Binding When a superclass variable references a subclass object, a potential problem exists: What if the subclass has overridden a method in the superclass, and the variable makes a call to that method? Does the variable call the superclass's version of the method, or the subclass's version? The variable calls the subclass's version of the method.

7 I.2 Polymorphism and Dynamic Binding GradedActivity exam; exam = new PassFailActivity(60); exam.setScore(70); System.out.println(exam.getGrade() ); The process of matching a method call with the correct method definition is known as binding. Java performs dynamic binding or late binding when a variable contains a polymorphic reference. JVM determines at runtime which method to call, depending on the type of object that the variable references.

8

9

10 I.2 Polymorphism and Dynamic Binding We can also use parameters to accept arguments to methods polymorphically. public static void displayGrades(GradedActivity g) { System.out.println(“Score “ + g.getScore() + “, grade “ + g.getGrade()); } GradedActivity e1 = new FinalExam(50,7); GradedActivity e2 = new PassFailActivity(70); GradedActivity e3 = new PassFailExam(100, 10, 70); displayGrades(e1); displayGrades(e2); displayGrades(e3);

11 I.3 The “is-a” Relationship Does Not Work in Reverse GradedActivity activity = new GradedActivity(); FinalExam exam = activity; // ERROR GradedActivity activity = new GradedActivity(); FinalExam exam = (FinalExam) activity; // Will compile but not run

12 I.4 The instanceof Operator The instanceof operator is used to determine whether an object is an instance of a particular class. refVar instanceof ClassName Returns true if the object referenced by refVar is an instance of ClassName.

13 I.4 The instanceof Operator GradedActivity activity = new GradedActivity(); if(activity instanceof GradedActivity) System.out.println(“Yes, activity is a GradedActivity”); else System.out.println(“No, activity is not a GradedActivity”); The instanceof operator understands the “is-a” relationship that exists when a class inherits from another class. FinalExam exam = new FinalExam(20, 2); if(exam instanceof GradedActivity) System.out.println(“Yes, exam is a GradedActivity”); else System.out.println(“No, activity is not a GradedActivity”);

14 Checkpoint 11.18 Consider the Rectangle and Cube classes as shown in the following figure

15 Checkpoint a. Is the following statement legal or illegal? If it is illegal, why? Rectangle r = new Cube(10, 12, 5); b. If you determined that the statement in part a is legal, are the following statements legal or illegal? System.out.println(r.getLength()); System.out.println(r.getWidth()); System.out.println(r.getHeight()); System.out.println(r.getSurfaceArea()); c. Is the following statement legal or illegal? Why? Cube c = new Rectangle(10, 12);

16 II. Abstract Classes and Abstract Methods An abstract method is a method that appears in a superclass, but expects to be overridden in a subclass. An abstract method has only a header and no body. AccessSpecifier abstract ReturnType MethodName(ParameterList); When an abstract method appears in a class, the method must be overridden in a subclass. If a subclass fails to override the method, an error will result. Abstract methods are used to ensure that a subclass implements the method.

17 II. Abstract Classes and Abstract Methods When a class contains an abstract method, we cannot create an instance of the class. Abstract methods are commonly used in abstract classes. An abstract class is not instantiated itself, but serves as a superclass for other classes. The abstract class represents the generic or abstract form of all the classes that inherits from it.

18 II. Abstract Classes and Abstract Methods A class becomes abstract when you place the abstract keyword in the class definition. AccessSpecifier abstract class ClassName {.... }

19 II. Abstract Classes and Abstract Methods An example: Students: Computer science students Biology students Computer science students take courses in different disciplines than those taken by biology students. It stands to reason that the number of remaining hours of computer science students to be taken is different from the number of remaining hours of biology students.

20 II. Abstract Classes and Abstract Methods The Student class holds data common to all students, but does not hold all the data needed for students of specific majors. Student's name, ID number, year admitted. A constructor toString method An abstract method named getRemainingHours. The CompSciStudent class represents students of specific major, a computer science student. The BiologyStudent class holds data for a biology student.

21 II. Abstract Classes and Abstract Methods UML class diagram The name of abstract class and the names of abstract methods are shown in italics.

22 II. Abstract Classes and Abstract Methods

23

24

25 ClassB must be an abstract class

26 Checkpoint 11.19 What is the purpose of an abstract method? 11.20 If a subclass extends a superclass with an abstract method, what must you do in the subclass? 11.21 What is the purpose of an abstract class? 11.22 If a class is defined as abstract, what can you not do with the class?

27 III.1 Interfaces An interface is similar to an abstract class that has all abstract methods. It can not be instantiated. All methods listed in an interface must be written elsewhere. The purpose of an interface is to specify behavior for a class. public interface InterfaceName { (Method headers …) }

28 III.1 Interfaces An Example: We need to compare scores of the graded activities. We must define some methods such as equals, isGreater, isLess in the activity classes. We can define these methods in the classes: GradedActivity FinalExam, … We should define an interface which has three declarations of these methods. This interface specifies behavior in comparison for all graded activities.

29 III.1 Interfaces public interface Relatable { boolean equals(GradedActivity g); boolean isGreater(GradedActivity g); boolean isLess(GradedActivity g); } This interface specifies methods that presumably, make relational comparisons with GradedActivity objects. No access specifier is used with the method header because all methods specified by an interface are public.

30 III.1 Interfaces In order for a class to use an interface, it must implement the interface. The class must provide all of the methods that are specified by the interface. With exact signatures specified and with the same return type. The interface is like a “contract”, and the class must adhere to the contract.

31 III.1 Interfaces public class FinalExam3 extends GradedActivity implements Relatable { … boolean equals(GradedActivity g) { … } boolean isGreater(GradedActivity g) { … } boolean isLess(GradedActivity g) { … }... }

32

33

34

35 III.2 Fields in Interfaces An interface can contain field declarations, but all fields in an interface are treated as final and static. Any class that implements this interface has access to these fields. public interface Doable { int FIELD1 = 1; int FIELD2 = 2; (Method headers …) }

36 III.3 Implementing Multiple Interfaces Java allows a class to implement multiple interfaces. When a class implements multiple interfaces, it must provide the methods specified by all of interfaces. public class MyClass implements Interface1, interface2, Interface3 { … }

37 III.4 Polymorphism and Interfaces We can create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its type.

38

39

40

41

42 III.4 Polymorphism and Interfaces RetailItem item1 = new CompactDisc(“Songs From the Heart”, “Billy Nelson”, 18.95); RetailItem item2 = new DvdMovie(“Planet X”, 102, 22.95); There are some limitation to using interface reference variables: When an interface variables references an object, we can use the interface variable to call only the methods that are specified in the interface. System.out.println(item1.getRetailPrice()); //OK System.out.println(item1.getTitle()); //ERROR

43 III.4 Polymorphism and Interfaces It is possible to cast an interface reference variable to the type of the object it references, and then call methods that are members of that type. RetailItem item1 = new CompactDisc(“Songs From the Heart”, “Billy Nelson”, 18.95); System.out.println((CompactDisc)item1.getTitle()) ;

44 Checkpoint 11.23 What is the purpose of an interface? 11.24 How is an interface similar to an abstract class? 11.25 How is an interface different from an abstract class, or any class? 11.26 If an interface has fields, how are they treated? 11.27


Download ppt "Chapter 11 Polymorphism. Contents I. Polymorphism 1. Polymorphism 2. Polymorphism and Dynamic Binding 3. The “is-a” Relationship Does Not Work in Reverse."

Similar presentations


Ads by Google