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

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
OOP: Inheritance By: Lamiaa Said.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Inheritance In object-oriented programming, a mechanism called inheritance is used to design two or more entities that are different but share many common.
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Inheritance in Java CS 3331 Fall Outline  Overloading  Inheritance and object initialization  Subtyping  Overriding  Hiding.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Intro to OOP with Java, C. Thomas Wu
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 13 Inheritance and Polymorphism.
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 10 Inheritance and Polymorphism
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
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.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Java Interfaces CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (see Chapter 9 of.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance-Basics.
Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Modern Programming Tools And Techniques-I Inheritance
Overloading and Constructors
Inheritance Basics Programming with Inheritance
Inheritance, Polymorphism, and Interfaces. Oh My
Chapter 9: Polymorphism and Inheritance
Computer Programming with JAVA
Java – Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance in Java CS 3331 Fall 2009.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Computer Science II for Majors
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
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

Student with two subclasses Student setTestScore getTestScore NUM_OF_TESTS 3 courseGrade name test[ ] … GraduateStudent computeGrade UndergraduateStudent computeGrade We will define three classes: Student GraduateStudent UndergraduateStudent We will define three classes: Student GraduateStudent UndergraduateStudent Implementation of computeGrade is unique to each subclass.

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