When is an explicit object reference casting is required?
General speaking, if the left hand side of an assignment is a more specific type (subtype) and the right hand side is a more general type (supertype), then explicit casting is required. On the other hand, when you assign a subclass reference to a variable of superclass, the casting is performed automatically, or not required.
Another case is calling methods from an object reference, you can not access methods that are only declared and implemented in its subclass. You have to explicit cast the object reference into the actual object type.
For example,
class Super {
}
class Sub extends Super {
public void writeLog() {
System.out.println("log");
}
class Program {
public static void main(String[] args) {
Sub b = new Sub();
// sub type reference can be assigned to super type without casting
Super a = b;
// super type reference has to be casted before assigned to sub type
b = (Sub)a;
((Sub)a).writeLog(); // method only defined in sub type
}
}
Java compiler is not responsible for checking if the casting is correct or not, just like some of the bindings only occur at run time ( XyzWs Java FAQ: Run time binding or compile time binding?). Java virtual machine does the checking at run time to find out whether the actual reference object is a legitimate object of the new type. If not, there will be a runtime exception: ClassCastException.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?