Inheritance and Polymorphism - PowerPoint PPT Presentation

About This Presentation
Title:

Inheritance and Polymorphism

Description:

Abstract classes are blueprints, interfaces are contracts. Interface: 'Here's some methods. ... Abstract class: 'Here's a blueprint for a class. ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 32
Provided by: webIcs
Category:

less

Transcript and Presenter's Notes

Title: Inheritance and Polymorphism


1
Inheritance and Polymorphism Recitation
10/(16,17)/2008
CS 180 Department of Computer Science, Purdue
University
2
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

3
Overloading of Methods and Constructors
  • Def. Overloading
  • The ability to allow different methods or
    constructors of a class to share the same name.

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

5
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()) //
6
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.

7
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

8
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

9
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.

10
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(Bs constructor args )
  • You must use the keyword super to call the
    superclass constructor. Invoking a superclass
    constructors name in a subclass causes a syntax
    error.

11
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

12
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
13
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 //
...
14
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

15
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

16
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.

17
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.getMaxCredi
ts() // which maxCredits method?
18
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.

19
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)
20
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 objects class.
  • Requires that the superclass have the inherited
    data or method

21
Student with two subclasses
We will define three classes Student Gradua
teStudent UndergraduateStudent
Implementation of computeGrade is unique to each
subclass.
22
Creating the roster Array
roster is an array of Student objects.
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)
Create instances of the subclasses of Student.
23
Processing the roster Array
  • Notice how the polymorphism is used above. The
    particular computeGrade() method to be called is
    dependent on value of i (dynamic binding)
  • If rosteri refers to a GraduateStudent, then
    the computeCourseGrade method of the
    GraduateStudent class is executed.
  • If rosteri refers to an UndergraduateStudent,
    then the computeCourseGrade method of the
    UndergraduateStudent class is executed.

24
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

25
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

26
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.

27
Sample Abstract Class
Abstract method has no method body.
Abstract method must be fully implemented in the
derived class.
28
Interfaces
  • An interface specifies the headings for methods
    that must be defined for any class that
    implements the interface.
  • Example -

29
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.

30
Abstract Class vs. Interface
  • Abstract classes are blueprints, interfaces are
    contracts
  • Interface Heres 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 Heres 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

31
Quiz Print the Output
Shape s new Shape9 // Fill up the
array with shapes for(int i 0 i lt
s.length i) if(i20) si new
Circle() else if (i30) si new
Square() else si new
Traingle() // Make polymorphic method
calls for(int i 0 i lt s.length i)
si.draw()
  • 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()")
Write a Comment
User Comments (0)
About PowerShow.com