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

## Presentation on theme: "Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University."— Presentation transcript:

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 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 constructors of a class to share the same name. 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() { /* … */ } // … } constructor overloading method overloading

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 p1 = new Point(); // which constructor? Point p2 = new Point(10,20); p2.distance(p1); // which method? p2.distance(20,30); p2.distance();

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 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) 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 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  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 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 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 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 = new S(); public class S extends T { int y = 30; // third public S( ) { super(); y = 40; // fourth } public class T { int x = 10; // first public T() { x = 20; // second } //... }

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 writeOutput() { … } } public class Student extends Person { public void writeOutput() { … } } Person p = new Person(); Student s = new Student(); p.writeOutput(); // invoke method of class Person s.writeOutput(); // invoke method of class Student

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.writeOutput();  The above line in the Student class would call the overridden writeOutput() 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 at runtime by the runtime type of the object, not by the declared type (static type). class Student { public int maxCredits() { return 15; } … } class GraduateStudent extends Student { public int maxCredits() { return 12; } … } Student s, s1; s = new Student(); s.getMaxCredits(); // which maxCredits method? s1 = new GraduateStudent(); S1.getMaxCredits(); // which maxCredits method?

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 someMethod() { … } The method someMethod() will not be overridden in any sub-class.

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 public void p(int i) { System.out.println(i); } 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 overloads method in B public void p(double i) { System.out.println(i); }

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

Creating the roster Array Student roster[ ] = new Student[40]; roster[0] = new GraduateStudent( ); roster[1] = new UndergraduateStudent( ); roster[2] = new UndergraduateStudent( ); roster[3] = new GraduateStudent( ); 0123436373839 roster Graduate- Student Under- graduate- Student Graduate- Student roster is an array of Student objects. Create instances of the subclasses of Student. Create instances of the subclasses of Student. (An object of a derived class can serve as an object of base class - Vice versa is WRONG)

Processing the roster Array for (int i = 0; i < numberOfStudents; i++ ) { roster[i].computeGrade( ); }  Notice how the polymorphism is used above. The particular computeGrade() method to be called is dependent on value of i (dynamic binding)  If roster[i] refers to a GraduateStudent, then the computeCourseGrade method of the GraduateStudent class is executed.  If roster[i] refers to an UndergraduateStudent, then the computeCourseGrade method of the UndergraduateStudent class is executed.

Static and Dynamic Binding Binding: determining the memory addresses for jumps Static: done at compile time  also called offline Dynamic: done at run time Compilation is done 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 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 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 computeGrade( );... } class GraduateStudent extends Student {... public void computeGrade( ) { //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 class that implements the interface. Example -

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 CS180 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 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 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.” Abstract method headers Methods Variables A class can extend only one class Cannot instantiate

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

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

Similar presentations