Upcasting and Downcasting:-
(Upcasting and Downcasting ) Java support Run-time polymorphism with the help of method overriding. Method overriding only applicable when the signature (prototype, return type, name, argument) of the superclass is the same as the subclass method, then it is known as method overriding.
- Dynamic method dispatch allows Java to support overriding of methods that is the object of run-time polymorphism.
- Overriding supports the concept of dynamic method dispatching. dynamic method dispatching possible by two different ways.
- Upcasting
- Downcasting
Upcasting
When the base class reference referred to the object of the child class is the concept of upcasting in Java.
Upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the supertype
Example
interface Test { void show(); void dis(); } class Demo implements Test { public void show() { System.out.println("show()...................."); } public void dis() { System.out.println("dis()......................."); } public void fun()
{
System.out.println("fun()...........................");
}
public static void main(String[] args)
{
Test t=new Demo();
t.show();
t.dis();
}
}
Output :-
show()....................
dis().......................
Downcasting
When the subclass reference referred to the object of the superclass is known as downcasting in java.
When we want to access specific behaviors of a subtype downcasting is used.
Example
class Test { } class Demo extends Test { public static void main(String[] args) { Demo d1=(Demo)new Test(); try { Demo d1=(Demo)new Test(); } catch(ClassCastException) { System.out.println("Down casting.........."); } } }
4 replies on “Upcasting and Downcasting in java”
I went over this web site and I believe you have a lot of great information, saved to bookmarks (:.
Thanks for giving the feedback
Hi there, just wanted to say, I liked this article. It was helpful. Keep on posting!
Thanks for giving the feedback.