- A Child class object can be assigned to Base class reference
- Assume class Customer is base class of RegularCustomer class
- The parent class reference can be used to invoke child class methods
- Only the methods which are overridden by child class and other method of parent class can not be accessed by Parent class reference.
- JVM bind the method to its linking based on the data type of Object referred by it, NOT by data type of reference.
- This decision is taken at Run time and hence it is called as Dynamic binding
- The binding of method call to its definition happens at run-time
- Dynamic binding is also called run-time polymorphism and late binding
- An instance of subclass can be casted to its parent class without explicit typecasting
- Explicit type casting can be done only between Sub class and super class
Customer cObject = new RegularCustomer
RegulatCustoomer = ( RegularCustomer )cObject;
Note : Typecasting can not be done between subclasses vice
versa.
2.
Similarly if cRef (in the example
given in the slide) refers to Customer class , then the following typecasting
is not valid :
Customer
cRef=new Customer();
RegularCustomer rRef=(RegularCustomer)cRef;
Method Overloading vs Method Overriding

Self study
What is the output of the following?
class Base{
private static int baseVar=0;
public static int commonVar=0;
public Base(){
baseVar++;
}
protected void printDetails(){
System.out.println("BaseVariable:"+baseVar);
}
}
class Derived extends Base{
private static int derVar=0;
public Derived(){
commonVar++;
derVar++;
}
public void printDetails(){
super.printDetails();
System.out.println("Derived
variable: "+derVar);
System.out.println("CommonVar:"+commonVar);
}
public static void
main(String args[]){
Derived childOne=new
Derived();
Derived childTwo=new
Derived();
Base baseOne=new
Base();
childTwo.printDetails();
}
}
output: ?
2.class Base{
private int baseVar=1000;
public Base(){
baseVar++;
}
public void
display(){
System.out.println("Base
Variable:"+baseVar);
}
}
class Derived extends Base{
private int derVar;
public Derived(int derVar){
this.derVar=derVar;
}
public void
display(){
System.out.println("Base
Variable:"+baseVar+"Derived Variable:"+derVar);
}
}
class Demo{
public static void
main(String args[]){
Base baseOne=new
Base();
baseOne.display();
Derived derOne=new
Derived(10);
derOne.display();
}
}
Output: ??
0 comments :
Post a Comment