wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes DOUBT on DOWNCASTING Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "DOUBT on DOWNCASTING" Watch "DOUBT on DOWNCASTING" New topic


debasmita pattnayak
Ranch Hand

Joined: Apr 12, 2007
Posts: 94
i am really confused with the concept of downcasting.can anyone explain me in context to the following question:

class Vehicle {}
class Car extends Vehicle {}

class VarArgSeven {
public static void washVehicle(Vehicle ... v) {
for(Vehicle vv : v) {
Car c = (Car)vv;
public static void main(String[] args) {
//insert the line here

Options :

a) washVehicle(new Car[] { new Car()});
b) washVehicle(new Vehicle[]{new Car(), new Vehicle()});
c) washVehicle(new Car(), new Car());
d) washVehicle(new Vehicle(), new Vehicle());
e) none of the above.

the answer to this is a and c but why not b and d too.
please explain.

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The reason is that even though Car extends Vehicle, if the runtime type of an object is Vehicle, you cannot refer to it as a Car.
debasmita pattnayak
Ranch Hand

Joined: Apr 12, 2007
Posts: 94
hi keith,
thanks for the reply...
i want to know then when is downcasting needed and what is the legal way of doing that? can you please sustain the same with an example
thanks in advance!
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
debasmita pattnayak
Ranch Hand

Joined: Apr 12, 2007
Posts: 94
thanks a lot!
now its more clear to me than before.
wood burning stoves
Similar Threads
Help in generics....
Can any one explain me this
need reply
object ref types trip me up all the time