Upcast and Downcast in Java
Upcast means to create an object of the sub(child) class and access methods and variables of the child class using the child class object.
package Tutorial_01;
public class MainClass extends TestOne{
int x = 50000;
void TestResult()
{
System.out.println("Child Class Values...:"+x);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
///-------------Upcast Example--------------------------------------
MainClass z = new MainClass(); // new object(child class object)
z.TestResult();
}
}
Downcast means to create an object of extend class (parent class) and access methods and variables of parent class using parent class object.
package Tutorial_01;
public class TestOne {
int x = 1000;
void TestResult()
{
System.out.println("Parent Class Values...:"+x);
}
}
package Tutorial_01;
public class MainClass extends TestOne{
int x = 50000;
void TestResult()
{
System.out.println("Child Class Values...:"+x);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
////----------DownCast Example----------------------------------------
TestOne y = new TestOne(); // new obj (parent class object)
y.TestResult();
}
}