Follwing Blog is about Upcasting and Downcasting In Java. Upcasting
Upacsting Is a concept used to support Runtime Polymorphism in which Parent Class refernce variable can hold child value Syntax
A ob=new B(); // Memory of B is allocated to Object of A
It is to be Noted that Upcasting Never Fails. When we are upcasting we can use only method or function which is a part of parent but called through child object.
Downcasting Downcasting is also a way to casting reference of Child Class to one of its Parent Class
B ob=(A)x; // Instance of A is allocated to B Object
It Is to be noted that Downcasting may Fails.
Following Program helps you to clear all doubts u are having...
public class A {
public void Show()
{
System.out.println("Calling from A's Show()");
}
}
public class B {
public void Show()
{
System.out.println("Calling from B's Show()");
}
public void Display()
{
System.out.println("Calling from B's display()");
}
}
public class Demo {
public static void main(String ar[])
{
A x=new B(); // Upcasting
x.show();
B y=(B)x; // Downcasting
y.Display();
}
}
0 Comment(s)