You are on page 1of 23

Inheritance and

Interfaces
ADAPTED FROM
WWW.CS.UTEP.EDU/VLADIK/CS2401.10A/CH_11_INHERITANCE_P
OLYMORPHISM.PPT
Recap: Relationship Between Objects
and Object References
For object references, the reference is copied:
person2 = person1
Two or more references can refer to the same object; these references
are called aliases of each other.

Before After
person person person1 person2
1 2

One object (and its data) can be accessed using different references 2
References and Inheritance
An object reference can refer to an object of its class, or to an
object of any class derived from it by inheritance
For example, if the Shape class is used to derive a child class called
Rectangle, then a Shape reference could actually be used to point to a
Rectangle object
Shape
Shape s;
s = new shape();

s = new Rectangle();
Rectangle

3
References and Inheritance

Shape myShape = new Circle(); // allowed.is a relationship


Shape myShape2 = new Rectangle(); //allowed
Rectangle myRectangle = new Shape(); // NOT allowed. Not is a
relationship

4
References and Inheritance
Assigning an object to an ancestor reference is considered to be a
widening conversion, and can be performed by simple assignment
Assigning an ancestor object to a reference can also be done, but it is
considered to be a narrowing conversion and must be done with a cast
Shape s = new Rectangle();

Rectangle c1 = new Rectangle ();


Shape s = c1;
Rectangle c2 = (Rectangle) s;

The widening conversion is the most useful


◦ for implementing polymorphism
5
References and Inheritance
Through a given type of reference variable, we can invoke only the
methods defined in that type class Shape
{
public void display()
{…}
Shape s;
}
s = new Rectangle();
class Rectangle extends Shape
{
public void display()
{…}
public void IncreaseLength()
{…}
Can we do the following statements: }
s.display();
s.IncreaseLength();

6
References and Inheritance
Through a given type of reference variable, we can invoke only the methods defined in that type

class Shape
{
public void display()
Shape s; {…}
s = new Rectangle(); }
class Rectangle extends Shape
{
public void display()
{…}
public void IncreaseLength()
Can we do the following statements: {…}
}
s.display(); Yes
s.IncreaseLength(); NO

7
References and Inheritance
We can “promote” an object back to its original type through an
explicit narrowing cast:
Shape s = new Rectangle();
s.display();

Rectangle c = (Rectangle) s;
c. IncreaseLength();

Question: which display() will be invoked by the line:


s.display();

8
References and Inheritance
We can “promote” an object back to its original type through an
explicit narrowing cast:
Shape s = new Rectangle();
s.display();

Rectangle c = (Rectangle) s;
c. IncreaseLength();

Question: which display() will be invoked by the line:


s.display();

Concept – Dynamic Method Dispatch – Will see in later slides

9
References and Inheritance
Shape s = new Circle();//allowed

Circle c = new Shape();//not


allowed

Circle c = (Circle)new Shape();


// allowed by generates run time
error. Not “is a relationship”

Source: https://www.studytonight.com/java/instanceof-operator.php

10
Summary of the Allowed Assignments Between Superclass
and Subclass Variables
There are four ways to assign superclass and subclass references to
variables of superclass and subclass types.
▪ Assigning a superclass reference to a superclass variable is
straightforward.
▪ Assigning a subclass reference to a subclass variable is
straightforward.
▪ Assigning a subclass reference to a superclass variable is safe,
because the subclass object is an object of its superclass.
▪ The superclass variable can be used to refer only to superclass members.
▪ If this code refers to subclass-only members through the superclass variable, the
compiler reports
Source: errors.
https://www.cs.drexel.edu/~spiros/teaching/SE102/slides/jhtp9_ch10b.ppt
Summary of the Allowed Assignments Between Superclass and
Subclass Variables
Attempting to assign a superclass reference to a subclass variable is a
compilation error.
▪ To avoid this error, the superclass reference must be cast to a subclass type
explicitly (downcasting).
▪ At execution time, if the object to which the reference refers is not a subclass
object, an exception will occur.

▪ instanceof operator is used to ensure that such a cast is performed only if the
object is a subclass object.

Source: https://www.cs.drexel.edu/~spiros/teaching/SE102/slides/jhtp9_ch10b.ppt
Instanceof Opertaor
• The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface).
• The instanceof in java is also known as type comparison
operator because it compares the instance with type.
• It returns either true or false. If we apply the instanceof operator with
any variable that has null value, it returns false.
class Simple1{  
 public static void main(String args[]){  
 Simple1 s=new Simple1();  
 System.out.println(s instanceof Simple1);//true  
 }  

13
Polymorphism in the context of
Inheritance
▪ Method overriding forms the basis for one of Java’s most powerful
concepts: dynamic method dispatch.
▪ Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
▪ Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.
▪In this process, an overridden method is called through the reference
variable of a superclass.
▪ The determination of the method to be called is based on the object
being referred to by the reference variable.
Upcasting
• If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example:

15
class A{ interface I
{
}   }  
class A
{
class B extends A }  
class B extends A implements I
{ {
}   }  
Here, the relationship of B class would be:
A a=new B();//upcasting   B IS-A
A B IS-A I
B IS-A Object
For upcasting, we can use the Since Object is the root class of all classes in Java,
reference variable of class type so we can write B IS-A Object.

or an interface type. For


Example:
16
Example
• In this example, we are creating two classes class Bike{  
Bike and Splendor.   void run(){System.out.println("running");}  
• Splendor class extends Bike class and }  
overrides its run() method. class Splendor extends Bike{  
• We are calling the run method by the   void run()
reference variable of Parent class. {System.out.println("running safely with 60km");
}  
• Since it refers to the subclass object and
  
subclass method overrides the Parent class
method, the subclass method is invoked at   public static void main(String args[]){  
runtime.     Bike b = new Splendor();//upcasting  
• Since method invocation is determined by     b.run();  
Output: running
the JVM not compiler, it is known as   }  
safely with
runtime polymorphism. }  60km.
17
Downcasting with java
instanceof operator
• When Subclass type refers to the object of Parent class, it is known as
downcasting. If we perform it directly, compiler gives Compilation
error. If you perform it by typecasting, ClassCastException is thrown
at runtime. But if we use instanceof operator, downcasting is possible.
Dog d=new Animal();//Compilation error  
• If we perform downcasting by typecasting, ClassCastException is
thrown at runtime.
Dog d=(Dog)new Animal();  
//Compiles successfully but ClassCastException is thrown at runtime

18
Down casting with instance of Down casting without
instance of
class Animal { 
}   
class Dog3 extends Animal {   class Animal { }  
  static void method(Animal a) {   class Dog4 extends Animal {  
    if(a instanceof Dog3){     static void method(Animal a) {  
       Dog3 d=(Dog3)a;//downcasting          Dog4 d=(Dog4)a;//downcasting  
       System.out.println("ok downcastin        System.out.println("ok downcasti
g performed");   ng performed");  
    }    }      }  
  public static void main (String [] args)
   public static void main (String [] arg
 {  
    Animal a=new Dog3();   s) {  
    Dog3.method(a);       Animal a=new Dog4();  
  }   }      Dog4.method(a);  
  } } 
Output:
ok downcasting performed Output:
ok downcasting performed
19
Run time Polymorphism
• Runtime polymorphism or Dynamic Method Dispatch is a process
in which a call to an overridden method is resolved at runtime rather
than compile-time.
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called
is based on the object being referred to by the reference variable.

20
Java Runtime Polymorphism Example: Bank
• Consider a scenario where Bank is a class that provides a method to
get the rate of interest. However, the rate of interest may differ
according to banks. For example, SBI, ICICI, and AXIS banks are
providing 8.4%, 7.3%, and 9.7% rate of interest.

21
Example
class Bank{   class TestPolymorphism{  
float getRateOfInterest(){return 0;}   public static void main(String args[]){  
}   Bank b;  
class SBI extends Bank{   b=new SBI();  
float getRateOfInterest(){return 8.4f;}   System.out.println("SBI Rate of Interest: "+
b.getRateOfInterest());  
}   b=new ICICI();  
class ICICI extends Bank{   System.out.println("ICICI Rate of Interest: "
float getRateOfInterest(){return 7.3f;}   +b.getRateOfInterest());  
}   b=new AXIS();  
class AXIS extends Bank{   System.out.println("AXIS Rate of Interest: "
float getRateOfInterest(){return 9.7f;}   +b.getRateOfInterest());  
}   }  

22
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

23

You might also like