Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.457 :

Posted: Tue Nov 06, 2012 9:22 pm
by ETS User
Hello, the very first line in explanation says:
The line 1 will be allowed during compilation, since assignment is done from a subclass reference to a superclass reference.
which refers to the code line 1 here:

Code: Select all

      A[] a, a1;
      B[] b;
      a = new A[10]; a1  = a;
      b =  new B[20];
      a = b;  // 1
      b = (B[]) a;  // 2
      b = (B[]) a1; // 3
   }
}
class A { }
class B extends A { }
since class A is a superclass of class B, how come a=b is subclass to superclass cast, this one requires an explicit cast!

Re: About Question com.enthuware.ets.scjp.v6.2.457 :

Posted: Wed Nov 07, 2012 6:13 am
by admin
Think of it like this. A is Automobile and B is Car (because it is given that B extends A, so Car extends Automobile).
Now, a = b; where a is of type Automobile and b is of type Car. This implies, you are trying to assign a Car to a reference of type Automobile, which is ok because a Car is always an Automobile.

Had it been b = a; i.e. car = auto; this would require a cast, because not every Automobile is a Car.

HTH,
Paul.