• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

DOUBT on DOWNCASTING

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
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;
System.out.print(c);
}
}
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.
thanks
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
debasmita pattnayak
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
thanks a lot!
now its more clear to me than before.
 
Listen. That's my theme music. That's how I know I'm a super hero. That, and this tiny ad told me:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic