Up Casting & Down Casting (Casting concept)
There are 2 types of casting they are,
1. Up casting 2. Down Casting
Up casting
Refer to the samples given below,
int x = 10; long y = 10;
- x = y -- wrong
- y = x -- correct (Because, according to the Hierarchy "long" is the higher one than "int")
class A {
}
class B extends A{
}
- A = B -- correct (Because super class has more power than sub class)
- B = A -- wrong
Refer these objects of the above code sample and select what's the wrong one.
- A a = new B (); -- correct (Because super class has more power than sub class)
- B b = new A (); -- wrong
- We cant assign the big one to the small one, but we can assign small one to the big one in Java.
- Assigning the small one to the big one is called upcasting. (The process that we put object of the sub class to the reference of the super class is called Up casting)
Down casting
- making the sub class reference again by the sub class object created by the super class reference is called down casting.
B b = a; --- WRONG (only for view)
B = Sub class reference
b = Sub class variable
a = super class variable
When down casting we will face 2 problems they are,
- You can't create an object without a reference in down casting.
- If we take the reference of the super class up casting will be a lie. (That means we can't assign big one by the small one.)
Then, How to down cast it?
You know that A (class reference) is stronger than a (class variable).
B b = (B) a; -- CORRECT
Because you know that a code like below is created.
class A{
}
Class B extends A {
}
- Here B is extended with A but we are representing A by putting B into the brackets of the object.


Comments
Post a Comment