Take one Super class and one sub Class.
public class ClassA {
public void callMe(){
System.out.println(" I am in Class A");
}
}
Sub Class :
public class ClassB extends ClassA {
What is Upcasting in Java?
System.out.println(" -------------------UpCasting Example --------------------- ");
ClassB childClassObject = new ClassB();
ClassA parentClassObject = new ClassA();
ClassA classAObject = childClassObject;
classAObject.callMe();
System.out.println("--------------------------------------------------------------");
What is DownCasting in Java?
System.out.println("-----------Down Casting Example-------------------------------");
ClassB classBObject = (ClassB) parentClassObject;
classBObject.callMe();
System.out.println("---------------------------------------------------------------");
Does Java Supports the DownCasting ?
Strictly Speaking No.
This is the Wonderful Link:
NOTES:
If an Class Object is upcasted to It's super class, then we cant allow you to use the properties
in that Class. It allows use only the Properties in the super class.
Example : Once an Object of Class Cat is upcasted to Animal Class. So Now onwards the object
of Cat behaves like an Object of Animal Class. So it is not allowed to use the Properties of
Cat Class.
Example :
public class ClassA {
public void callMe(){
System.out.println(" I am in Class A");
}
}
Sub Class :
public class ClassB extends ClassA {
public void callMe(){
System.out.println(" I am in Class B");
}
}
What is Upcasting in Java?
System.out.println(" -------------------UpCasting Example --------------------- ");
ClassB childClassObject = new ClassB();
ClassA parentClassObject = new ClassA();
ClassA classAObject = childClassObject;
classAObject.callMe();
System.out.println("--------------------------------------------------------------");
What is DownCasting in Java?
System.out.println("-----------Down Casting Example-------------------------------");
ClassB classBObject = (ClassB) parentClassObject;
classBObject.callMe();
System.out.println("---------------------------------------------------------------");
Does Java Supports the DownCasting ?
Strictly Speaking No.
This is the Wonderful Link:
NOTES:
If an Class Object is upcasted to It's super class, then we cant allow you to use the properties
in that Class. It allows use only the Properties in the super class.
Example : Once an Object of Class Cat is upcasted to Animal Class. So Now onwards the object
of Cat behaves like an Object of Animal Class. So it is not allowed to use the Properties of
Cat Class.
Example :
http://javaforyou.wordpress.com/2008/06/22/casting-reference-variables-downcasting-upcasting/