ClassCastException Adventure

Go To StackoverFlow.com

0

I have -

class A {
    // contains certain set() and get() methods
}

class B extends A {
    public A getAotherMethod() {
      A a = new A();
      // Contains some logic
      return a
      }
}

class C extends B {
    // contains certain set() and get() methods
}

class D {
    public Object getMethod() {

      B b = new B();
      // Contains some logic
      return b.getAnotherMethod()
     }
}


public static void main(String[] args) {
    A a = new A();
    B b = new B();
    C c = new C();
    D d = new D();
    c = (C) d.getMethod(); // This is giving me ClassCastException
}
2012-04-04 06:42
by hari
"I have a car. When I drive against a wall, it breaks. - Ingo 2013-07-25 10:27


6

d.getMethod();

This will call b.getAnotherMethod() internally, which has

A a = new A();
// Contains some logic
return a

The object of class A cannot cast to class C

We can assign subclass object to superclass reference but we cannot assign superclass object to subclass reference what is done by you in this case.

2012-04-04 06:45
by Chandra Sekhar
Ads