Reference Type Casting
Objects of classes also can be cast into objects of other classes when the source and destination classes are related by inheritance and one class is a subclass of the other. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java. There are two types of Reference Type Casting in Java, they are :
- Upcasting
- Downcasting
Upcasting is casting to a supertype, while downcasting is casting to a subtype. Supercasting is always allowed, but subcasting involves a type check and can throw a ClassCastException.
Upcasting
Casting a subtype object into a supertype and this is called upcast. In Java, we need not add an explicit cast and you can assign the object directly. Compiler will understand and cast the value to supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an explicit cast and no issues.
package com.test;
public class SuperClass {
public static void main(String[] args) {
SuperClass superClass = new SubClass();// Upcasting: SubClass is cast to SuperClass
}
}
class SubClass extends SuperClass{
}
Downcasting
Casting a supertype to a subtype is called downcast. This is the mostly done cast. By doing this we are telling the compiler that the value stored in the base object is of a super type. Then we are asking the runtime to assign the value. Because of downcast we get access to methods of the subtype on that object. When performing downcasting, that you’re well aware of the type of object you’ll be casting. But here there is danger of ClassCastException as in the case for the below example.
package com.test;
public class SuperClass {
public static void main(String[] args) {
SuperClass a = new SubClass();
SuperClass b = new SuperClass();
SubClass subClassA= (SubClass) a; // a refers to object type SubClass, so no issues here
SubClass subClassB= (SubClass) b; // b refers to object type SuperClass, so this throws //ClassCastException
}
}
class SubClass extends SuperClass{
}
Output:
Exception in thread “main” java.lang.ClassCastException: com.test.SuperClass cannot be cast to com.test.SubClass at com.test.SuperClass.main(SuperClass.java:8)