Site Search:

Determine when casting is necessary


Back OCAJP



After studying polymorphism and reference types, we understand an object can also be accessed via superclass and interface references. Different reference types, though all valid, have different access limit to the object. Superclass reference, though valid, lost access to those methods only defined in the subclass; interface reference, though also valid, can access only those methods specified in the interface; only when the reference type matches the object type, the reference have full access to the object methods. In case we need more access to the object, we want to do the type casting.

Casting from subclass to superclass don't need explicit type casting. Casting from a class to the interface that it implements also don't need explicit type casting. Casting from a class to an unrelated class results in compilation error. Casting from subclass to superclass won't create compiler error, but will results in runtimeException.


OCAJP>cat test.java 
import java.util.*;
class test {
  public static void main(String...args) throws Exception{
    canCry cancry = new subClass();  //cast to interface, lost method access
    class1 c1 = new subClass();  //cast to superclass, lost method access
    //class2 c2 = new subClass();  //error: incompatible types
    //class2 c22 = new class1();  //error: incompatible types 
    cancry.cry();
    //cancry.cryLow();  //error: cannot find symbol
    //cancry.cryLoud();  //error: cannot find symbol
    subClass cancrycast = (subClass)cancry;  //cast to implementing class, gain method access
    cancrycast.cryLow();
    cancrycast.cryLoud();
    System.out.println("class1 reference");
    c1.cry();
    c1.cryLow();
    //c1.cryLoud();  //error: cannot find symbol
    //(subClass)c1.cryLoud();  //error: not a statement
    System.out.println("class1 cast reference");
    subClass c1cast = (subClass)c1;  //cast to subclass, gain method access
    c1cast.cryLoud();  //cast type matches object type

    canCry cancry2 = new class1();
    class1 c12 = new class1();
    superClass su = (superClass)cancry2;  //cast type didn't match object type
    //superClass su2 = (superClass)c12;  //error: incompatible types
  }
}
interface canCry {
  public void cry();

class subClass extends class1 {
  public void cryLoud() {System.out.println("roar");}
}
class class1 implements canCry{
  public void cry() {System.out.println("class1 cry");}
  public void cryLow() {System.out.println("murmur");}
}

class class2 implements canCry {
  public void cry() {System.out.println("class2 cry");}
}

OCAJP>javac test.java 
OCAJP>java test
class1 cry
murmur
roar
class1 reference
class1 cry
murmur
class1 cast reference
roar
Exception in thread "main" java.lang.ClassCastException: class1 cannot be cast to superClass
at test.main(test.java:25)


Back OCAJP