Inheritance and Polymorphism Recitation 1016 172008 CS 180

  • Slides: 31
Download presentation
Inheritance and Polymorphism Recitation – 10/(16, 17)/2008 CS 180 Department of Computer Science, Purdue

Inheritance and Polymorphism Recitation – 10/(16, 17)/2008 CS 180 Department of Computer Science, Purdue University

Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class

Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab consulting hours to clarify all questions

Overloading of Methods and Constructors Def. Overloading The ability to allow different methods or

Overloading of Methods and Constructors Def. Overloading The ability to allow different methods or constructors of a class to share the same name. constructor overloading public class Point { public Point() { /* … */ } public Point(int x, int y) { /* … */ } public double distance(Point other) { /* … */ } public double distance(int x, int y) { /* … */ } public double distance() { /* … */ } // … } method overloading

Overloading (Cont. ) Which overloaded method to invoke? Resolved at compile-time with signature matching,

Overloading (Cont. ) Which overloaded method to invoke? Resolved at compile-time with signature matching, where signature is name and parameter types. Constructors/Methods 1: Point() 2: Point(int x, int y) 3: double distance(Point other) 4: double distance(int x, int y) 5: double distance() Point p 1 = new Point(); // which constructor? Point p 2 = new Point(10, 20); p 2. distance(p 1); // which method? p 2. distance(20, 30); p 2. distance();

When to Overload? When there is a common description of the functionality that fits

When to Overload? When there is a common description of the functionality that fits all the overloaded methods. public class String { public String substring(int i, int j) { // base method: return substring from index i to j - 1. } public String substring(int i) { // provide default argument return substring(i, length()); } // … }

Inheritance Inheritance models the is-a relationship. If class S extends class T, then all

Inheritance Inheritance models the is-a relationship. If class S extends class T, then all objects of S can act-like an object of T. Only single inheritance is allowed among classes. All public and protected members of a superclass are accessible in the subclasses.

Inheritance Contd. we can build class hierarchies using the keyword extends each child (subclass)

Inheritance Contd. we can build class hierarchies using the keyword extends each child (subclass) inherits all the data and methods of its parent (superclass) we can add new methods in the subclass, or override the inherited methods private data and methods are inherited, but cannot be accessed directly; protected data and methods can be accessed directly constructor methods must be invoked in the first line in a subclass constructor as a call to super

Inheritance Example Class C is a subclass of class B (its superclass) if its

Inheritance Example Class C is a subclass of class B (its superclass) if its declaration has the form class C extends B { … } The subclass extends properties and methods from superclass The superclass is a generalization of the subclass

Subclass Constructors When a subclass is created, java will call the superclass constructor first

Subclass Constructors When a subclass is created, java will call the superclass constructor first super(. . ) must be the first statement in subclass constructor If the superclass constructor is missing, then a no-arg super() is invoked implicitly It is advised to have a default constructor defined in every class so as to be accessed by subclass constructor Can also invoke another constructor of the same class. this(…) must be the first statement.

Example of “super” Calls The call to super must be the first statement in

Example of “super” Calls The call to super must be the first statement in the subclass constructor Example: class C extends B { … public C ( … ) { super(B’s constructor args ); … } You must use the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error.

Example on the Impact of a Superclass without no-arg Constructor Find the errors in

Example on the Impact of a Superclass without no-arg Constructor Find the errors in the program? public class Apple extends Fruit { } class Fruit { public Fruit(String name) { System. out. println("Fruit's constructor is invoked"); } } There is no default constructor in superclass

Example of “this” Calls public class Point { private int x, y; public Point(int

Example of “this” Calls public class Point { private int x, y; public Point(int x, int y) { this. x = x; this. y = y; } public Point() { // default constructor this(0, 0); } } this calls are used to avoid repeating code

Execution Order of Constructors Rule: Superclass first and field initialization first Example: S x

Execution Order of Constructors Rule: Superclass first and field initialization first Example: S x = new S(); public class S extends T public class T { { int x = 10; // first int y = 30; // third public T() { public S( ) { x = 20; // second super(); } y = 40; // fourth //. . . } } }

Overriding Methods Def. Overriding Refers to the introduction of an instance method in a

Overriding Methods Def. Overriding Refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method declared in the superclass. Consequences Implementation of the method in the subclass replaces the implementation of the method in the superclass

Overriding Methods (Cont. ) public class Person { public void write. Output() { …

Overriding Methods (Cont. ) public class Person { public void write. Output() { … } } public class Student extends Person { public void write. Output() { … } } Person p = new Person(); Student s = new Student(); p. write. Output(); // invoke method of class Person s. write. Output(); // invoke method of class Student

Calling Overriden Methods of Superclass super can be used to call a method in

Calling Overriden Methods of Superclass super can be used to call a method in the base class that has been overridden in the derived class. Example super. write. Output(); The above line in the Student class would call the overridden write. Output() method in the Person class. This need not be the first line of code. You cannot use super to invoke a method in some ancestor class other than the immediate base (parent) class.

Overriding Methods (Cont. ) Dynamic dispatch (binding): The method to be invoked is determined

Overriding Methods (Cont. ) Dynamic dispatch (binding): The method to be invoked is determined at runtime by the runtime type of the object, not by the declared type (static type). class Student { public int max. Credits() { return 15; } … } class Graduate. Student extends Student { public int max. Credits() { return 12; } … } Student s, s 1; s = new Student(); s. get. Max. Credits(); // which max. Credits method? s 1 = new Graduate. Student(); S 1. get. Max. Credits(); // which max. Credits method?

The final Modifier You can prevent a method definition from being overridden by adding

The final Modifier You can prevent a method definition from being overridden by adding the word final to the method heading. example public final void some. Method() { … } The method some. Method() will not be overridden in any sub-class.

Overloading Vs. Overriding public class Test { public static void main(String[] args) { A

Overloading Vs. Overriding public class Test { public static void main(String[] args) { A a = new A(); a. p(10); } } class B { public void p(int i) { } } class A extends B { // This method overrides the method in B //This method overloads method in B public void p(int i) { public void p(double i) { System. out. println(i); } }

Polymorphism Polymorphism allows a variable to refer to objects from different (but related by

Polymorphism Polymorphism allows a variable to refer to objects from different (but related by inheritance) classes. References to data or methods are correctly resolved according to the object’s class. Requires that the superclass have the inherited data or method

Student with two subclasses Student We will define three classes: NUM_OF_TESTS 3 Student course.

Student with two subclasses Student We will define three classes: NUM_OF_TESTS 3 Student course. Grade set. Test. Score name get. Test. Score test[ ] Graduate. Student compute. Grade Student Graduate. Student Undergraduate. Student Implementation of compute. Grade is unique to each subclass. … Undergraduate. Student compute. Grade

Creating the roster Array Student roster[ ] = new Student[40]; roster[0] roster[1] roster[2] roster[3]

Creating the roster Array Student roster[ ] = new Student[40]; roster[0] roster[1] roster[2] roster[3] roster Graduate. Student = = new new Graduate. Student( ); Undergraduate. Student( ); Graduate. Student( ); 0 Undergraduate. Student 1 2 Undergraduate. Student 3 4 Graduate. Student roster is an array of Student objects. Create instances of the subclasses of Create instances of the Student. (An object of subclasses of Student. a derived class can serve as an object of base class - Vice versa is WRONG) 36 37 38 39

Processing the roster Array for (int i = 0; i < number. Of. Students;

Processing the roster Array for (int i = 0; i < number. Of. Students; i++ ) { roster[i]. compute. Grade( ); } § Notice how the polymorphism is used above. The particular compute. Grade() method to be called is dependent on value of i (dynamic binding) § If roster[i] refers to a Graduate. Student, then the compute. Course. Grade method of the Graduate. Student class is executed. § If roster[i] refers to an Undergraduate. Student, then the compute. Course. Grade method of the Undergraduate. Student class is executed.

Static and Dynamic Binding: determining the memory addresses for jumps Static: done at compile

Static and Dynamic Binding: determining the memory addresses for jumps Static: done at compile time Dynamic: done at run time Compilation is done offline also called offline it is a separate operation done before running a program Binding done at compile time is, therefore, static Binding done at run time is dynamic also called late binding

Abstract Classes Often we want to place elements common to all subclasses in their

Abstract Classes Often we want to place elements common to all subclasses in their superclass But we do not want any instances to be created from the superclass In such case, we designate the superclass as an abstract class. This is also a way to enforce existence of methods in subclasses. Abstract classes are only used as super classes

Abstract Methods Abstract methods have no body at all and just have their headers

Abstract Methods Abstract methods have no body at all and just have their headers declared The only way to use an abstract class is to create a subclass that implements each abstract method It is common for an abstract class to include an abstract method that must be implemented by the sub classes. If a class includes an abstract method, then it is considered as an abstract class and must have the abstract modifier in the class declaration.

Sample Abstract Class abstract class Student {. . . abstract public void compute. Grade(

Sample Abstract Class abstract class Student {. . . abstract public void compute. Grade( ); . . . } class Graduate. Student extends Student {. . . public void compute. Grade( ) { //method body comes here }. . . } Reserved word abstract in the class declaration. Abstract method has no method body. Abstract method must be fully implemented in the derived class.

Interfaces An interface specifies the headings for methods that must be defined for any

Interfaces An interface specifies the headings for methods that must be defined for any class that implements the interface. Example -

Interfaces Contd. A class that implements an interface must implement all the methods specified

Interfaces Contd. A class that implements an interface must implement all the methods specified by the interface. To implement an interface, a class must include the phrase implements Interface_Name at the start of the class definition example class CS 180 implements Writable {…} implement all the method headings listed in the definition of the interface.

Abstract Class vs. Interface Abstract classes are blueprints, interfaces are contracts Interface: “Here’s some

Abstract Class vs. Interface Abstract classes are blueprints, interfaces are contracts Interface: “Here’s some methods. If your class implements this interface, you must provide an implementation of each method in the interface in the class. ” Method headers A class can implement multiple interfaces Cannot instantiate Abstract method headers Methods Variables A class can extend only one class Cannot instantiate Abstract class: “Here’s a blueprint for a class. If your class extends this abstract class, you can use any functionality here and add onto it, but you must fill in what I have not. ”

Quiz – Print the Output class Shape { void draw() {} } class Circle

Quiz – Print the Output class Shape { void draw() {} } class Circle extends Shape { void draw() { System. out. println("Circle. draw()"); } } class Square extends Shape { void draw() { System. out. println("Square. draw()"); } } class Triangle extends Shape { void draw() { System. out. println("Triangle. draw()"); } } Shape[] s = new Shape[9]; // Fill up the array with shapes: for(int i = 0; i < s. length; i++) { if(i%2==0) s[i] = new Circle(); else if (i%3==0) s[i] = new Square(); else s[i] = new Traingle(); } // Make polymorphic method calls: for(int i = 0; i < s. length; i++) s[i]. draw(); }