Domanda

given the following code, I have a question:

class A{}
class B extends A {}
class C extends B{}

public class Test {
    public static void main(String[] args) {
        A a = new A();
        A a1=new A();
        B b = new B();
//        a=b;// ok
//        b=(B)a;// ClassCastException
//        a=(A)a1;  // ok
//        a=a1;  // ok

        a=(B)a1;  // compiles ok, ClassCastException
    }
}

My question is with the line in bold. My understanding is that for the code to compile, it just needs to be satisfied that the classes are in the same hierarchy and as a result it may work (up the tree implicit casting, down the tree requires explicit casting). Whenever I have come across ClassCastException it is because the reference was pointing to an object up the tree e.g. a ref of type B pointing to an object of type A.

The line in question appears to be a ref of type A pointing to an object of type A. The cast to (B) obviously is what is causing the ClassCastException. Can someone explain please what it does to effect this?

Note: If a1 was pointing at an object of type B then it works (just tested it). So the downcast is legal regarding the compiler and it can be made to execute without an exception if the reference is pointing at an object of the correct type.

By casting the A ref a1 to a B and assigning it to a, it appears that the A ref a no longer expects to refer to an object of type A but a B?

Thanks, Sean.

PS I know this is a bit unusual, preparation for Java certification. Normally we downcast to the type on the left hand side e.g. b=(B)a; (and I can see why this gives a ClassCastException).

È stato utile?

Soluzione

All B's are A's, by inheritance. But not all A's are B's. This particular instance isn't, hence the runtime exception.

Altri suggerimenti

You are trying to cast a super class reference variable to a sub class type. You cannot do this. Think practical, a super class object cannot contain independent methods (other than the super class' methods) of the sub class.

At run-time you might call a method in the sub class which is certainly not in the super class object.

class A{
  public void foo(){}
}
class B extends A {
  public void bar(){}
}

Now,

A a=new A();
B b=(B)a;
b.bar();

When you call like this the compiler, will only check whether the method bar() existed in the class B. That's it. It doesn't care about what is in the 'object' because it is created at runtime.

But at runtime, as said before there is no bar() method in the object a. b is just a reference that is pointing to object a but a contains only foo() not bar()

Hope you understood. Thank you.

Downcasts are illegal. An A is not a B and therefore you can't cast it to be one. You can cast B to be A, but not the other way round.

In your code example, the variable a is a reference to an object of type A. The class B extends the class B, but the relationship between classes A and B can only be described as follows:

  1. Class B isa Class A (every object of type B can legally be cast to class A).
  2. Class A is-not-a Class B (you can never assign an rvalue of type B to a reference of type A).

This is legal: a = (A)b; because class B isa class A.

One way to think of it is class B is a superset of class A.

If A is a set that contains (1, 2) and B is a set that contains (1, 2, 3) then B is a superset of A (in java terms: B can be cast to A) but A is not a superset of B (A can not be cast to B).

From a different point of view:

  • Socrates was mortal.
  • All men are mortal.

Socrates (class B) isa man (class A).

This is an invalid minor assertion: All men are Socrates.

Remember that legal casts are ruled by the "IS-A" test, why you can compile your code?, because ClassCastException is an Unchecked Exception, since extends from RuntimeException

ClassCastException ---IS-A--> RuntimeException (Another example of a possible legal cast).

To downcast in Java, and avoid run-time exceptions, use the following code.

if (animal instanceof Dog) {
  Dog dogObject = (Dog) animal;
}

Animal is the parent class and Dog is the child class.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top