Upcasting and Downcasting (OOP - JAVA)
Upcasting and Downcasting
Upcasting
A object, a variable or a method inside a super class is accessed a object, a variable or a method in a sub class called Upcasting.
A a = new B();
- super class object reference - A
- reference variable - a
- sub class object reference - B
eg:
int x = 5;
long y = 5;
x = y; <= wrong way
y = x; <=correct way
eg:
double a = 7.88;
float b = 25.98f;
a = b; <=correct way
b = a; <=wrong way
Consider the following example.
class A{
}
class B extends A{
}
class Test{
A a = new A();
B b = new B();
b = a; <=wrong way
a = b; <=correct way
}
Downcasting
Sub class object which has been assigned to the Super class variable is converting to a sub class object called Downcasting.
consider the following example.
class A{
}
class B extends class A{
}
class Test{
A a = new A(); <=correct
B b = new B(); <=correct
A a = new B(); <=correct
B b = new A(); <=wrong
B b = a; <=wrong
B b = A a; <=wrong
B b = (B) a; <=correct
}

Comments
Post a Comment