1

I am getting an exception for the following code.

class A {
    void foo() {
        System.out.println("Running foo()");
    }
}

class B extends A {
    void foo() {
        System.out.println("Overidden foo()");
    }
}

public class Casting {
    public static void main(String[] args) {
        A obj = new B();
        obj.foo();

        // B ref = (B) obj;
        // ref.foo();

        B ref = (B) new A();
        ref.foo();
    }
}

But if I run

B ref = (B) obj;
ref.foo();

instead of

B ref = (B) new A();
ref.foo();

it works properly.

Can anyone explain what is happening here.?

M A
  • 71,713
  • 13
  • 134
  • 174

2 Answers2

1

It's pretty easy to explain.

By doing new A() you receive an A-object. Then you tell the JVM it's of type B, but that's obviously wrong and the JVM can't cast from A-type to B-type, how should Java know how to do that? It's not sure that A has the same methods as B. It's just a parent, B could have methods A hasn't. If you could cast from A to B you could have B objects that don't behave like B objects and don't have the B classes methods.

If you have a B-object you can treat it like a A-object because every B-object has at least the same methods, constructors and ivars.

An example using ducks:

Imagine you have got an abstract Duck class (but you didn't declared it as abstract). This class is the parent class of all other duck classes and also including RubberDuck. As reason of that the Duck class just has some basic methods like getSize but no method like walk or eat (a rubber duck can't eat herself).

What would happen if you create a duck object and downcast it to BuffleheadDuck and you would try to invoke the walk method? A BuffleheadDuck duck knows how to walk, but an abstract duck can't walk.

Community
  • 1
  • 1
idmean
  • 14,540
  • 9
  • 54
  • 83
1

obj is an instance of B because you created it using the contructor of class B. This is why B ref = (B) obj; works fine.

In B ref = (B) new A(); you are simply casting an object of type A created using the constructor of A (which is the parent class) to a subclass type which will cause a java.lang.ClassCastException. The opposite casting would work, i.e.

A ref = (A) new B();
ref.disp();

in which case you converting an instance of a subclass to its parent which is fine since an object of type B is also an instance of A.

M A
  • 71,713
  • 13
  • 134
  • 174