0

can we down cast super class if sub class belonngs to same hierarchy ?

example :

class Building { }
 public class Barn extends Building {
 public static void main(String[] args) {
 Building build1 = new Building();
 Barn barn1 = new Barn();
 //Barn barn2 = (Barn) build1; // line number 10
 Object obj1 = (Object) build1;
 //String str1 = (String) build1; // line number 12
 Building build2 = (Building) barn1;
 }
 }

Answer here states that only line 12 commented will make the code compile. But code is getting compiled only if even the line 10 is commented. please help.

user3066920
  • 31
  • 1
  • 8

2 Answers2

0

Since Building is not derived from Barn you will receive a ClassCastException. This exception is possible anytime you are performing an unchecked downcast.

Since Barn extends Building you would need to assign an instance of Barn to build1.

 Building build1 = new Barn();
 Barn barn2 = (Barn) build1;

As the documentation explains a class cast exception is thrown:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

Just because two classes are in the same class hierarchy does not mean we can freely down cast to any type in the hierarchy. The instance we are downcasting must be of the type we are downcasting to. Since the instance is created is of type Building which sets one level above Barn in the type hierarchy, it cannot be cast to a Barn.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • yes ...but in some sites people are explaining that down cast can be made possible if they belong to same hierarchy. Is that possible ...if so than can you pls expain ... – user3066920 Feb 22 '14 at 11:39
  • @user3066920 Yes that is entirely possible but a down cast, casts an instance of a superclass to a subclass. If the instance is **NOT** of the subclasses type this is illegal. – Kevin Bowersox Feb 22 '14 at 11:41
0

please see the following example

class SuperClass {
...
}

class SubClass extends SuperClass {
...

}

public class Program {
  public static void main(String[] args) {

// case 1: actual SuperClass object
    SuperClass p1 = new SuperClass(); 

// case 2: SubClass object is referred by a SuperClass reference 
    SuperClass p2 = new SubClass();   

    SubClass s1 = (SubClass)p1; //run time error
    SubClass s2 = (SubClass)p2; //OK
  }
}

Thank you good luck

T8Z
  • 691
  • 7
  • 17