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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

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

Post 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!

Online
admin
Site Admin
Posts: 10386
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests