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

Slides:



Advertisements
Similar presentations
Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Inheritance, Polymorphism, and Virtual Functions
Chapter 10: Inheritance and Polymorphism
Inheritance Chapter 11.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
11-1 Chapter.9 Classes & Objects: Inheritance –What Is Inheritance? –Calling the Superclass Constructor –Overriding Superclass Methods –Protected Members.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 11: Inheritance Starting Out with Java: From Control Structures through Data Structures Second.
Chapter Topics Chapter 10 discusses the following main topics:
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Inheritance Starting Out with Java: From Control Structures.
Inheriatance. 9-2 What is Inheritance? Generalization vs. Specialization Real-life objects are typically specialized versions of other more general objects.
More on Inheritance Chapter 11 Continued. Reminders Overloading – different signatures Overriding – same signatures Preventing overriding – use final.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
11-2  What Is Inheritance?  Calling the Superclass Constructor  Overriding Superclass Methods  Protected Members  Chains of Inheritance  The Object.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2010 Pearson Addison-Wesley. All rights reserved. AN INTRODUCTION TO INHERITANCE.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 11 Inheritance. Contents I.What Is Inheritance? II. Calling the Superclass Constructor III. Overriding Superclass Methods IV. Protected Members.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Modern Programming Tools And Techniques-I
Polymorphism, Abstract Classes & Interfaces
Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism
Inheritance, Polymorphism, and Virtual Functions
by Tony Gaddis and Godfrey Muganda
An introduction to inheritance
Starting Out with Java: From Control Structures through Objects
Java Programming Language
Inheritance, Polymorphism, and Interfaces. Oh My
Abstract Classes AKEEL AHMED.
Chapter 9: Polymorphism and Inheritance
Inheritance, Polymorphism, and Virtual Functions
Polymorphism, Abstract Classes & Interfaces
Introducing PA6 – The Last one
Java Inheritance.
Advanced Inheritance Concepts
Chapter 14 Abstract Classes and Interfaces
Chapter 8 Class Inheritance and Interfaces
Lecture 0311 – Polymorphism
Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Presentation transcript:

Chapter 11 Polymorphism

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

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.

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.

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

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.

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.

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

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

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.

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

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

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

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.

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.

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

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.

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.

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

II. Abstract Classes and Abstract Methods

ClassB must be an abstract class

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

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

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.

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.

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.

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

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

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

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.

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

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

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