This manual will specifically guide you about upcasting in Java.
What is Upcasting in Java?
When a child object is typecasted into the parent object, it is called Upcasting or Generalization. Upcasting is used implicitly and can allow you to access the parent class members.
Upcasting is usually not required in Java. But if you want to create a universal code that only works with the parent class, we need upcasting.
Syntax
The syntax of the Upcasting is given as:
Here the ChildClass object will be typecasted into the ParentClass object.
Example 1
In this example, we will use upcasting to access the members of the parent class using the child class object. Here, we have a parent class named ParentClass with a string type variable name and a method displayInfo():
String name;
void displayInfo()
{
System.out.println("Parent class method");
}
}
In the next step, we will create a child class named ChildClass that is inherited from the ParentClass by using the extends keyword. ChildClass overrides the ParentClass method named displayInfo():
void displayInfo()
{
System.out.println("Child class method");
}
}
While using typecasting, the ChildClass can only access the members of the ParentClass and the overridden methods in ChildClass.This operation will assist in implementing the Upcasting implicitly.
Now, we will typecast the child object into the parent object. pt is the object of the ParentClass, which is going to be typecast into the child object by using the new ChildClass() keyword. Now pt object can access the ParentClass properties and methods:
public static void main(String[] args) {
ParentClass pt = new ChildClass();
pt.name = "John";
System.out.println("Name :" + pt.name);
pt.displayInfo();
}
}
The output shows that the child object pt has successfully accessed the value of the ParentClass variable name and also executed the related displayInfo() method:
Example 2
Now, in the existing ChildClass, we will create an integer type variable named rollno:
Then, we will access these variables in the main() method by using the object pt. This operation will throw an Exception as in Upcasting ChildClass can only access the ParentClass properties and methods:
public static void main(String[] args) {
ParentClass pt = new ChildClass();
pt.name = "John";
pt.rollno=15;
System.out.println("Name :" + pt.name);
pt.displayInfo();
}
}
Output
If you want to access the ChildClass variables, you must create a ChildClass object as ChildClass cc = new ChildClass().
We presented all the necessary information related to Upcasting in Java.
Conclusion
Upcasting is a type of Object typecasting where the child object is typecasted in the parent object. It is also known as Generalization. Upcasting implements implicitly in Java, but it is used hardly. You can use Upcasting if you want to access the parent class properties, as it restricts access to the child class method. In this manual, we have explained Upcasting and its implementation in Java.