• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please Help me with this!!!  RSS feed

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Team,
I got a question which seems to be silly but need to get it cleared

I got two classes, vehicle and car class and car class extends vehicle

In car class i have

Vehicle x=new Vehicle();
Vehicle y=new Car();

I couldnt get whats the difference between these two statements??
With both x and y objects i am only able to access methods of vehicle but not car but however i know i can do this by Car c=new Car();
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You explicitly told the compiler that variable y is going to refer to Vehicle types. The compiler takes you at your word and only lets you do Vehicle things to that variable. In your sample statement you created a Car and made y refer to it, but later on you might make y refer to a Vehicle or a Truck or Motorcycle. The compiler can't guess about those things you might do, so it enforces the rule of only doing Vehicle things to y.

Say you have a Secretary who can also repair printers. You get in the habit of having him fix your printer. Then one day there is a substitute Secretary who is a really great Secretary but knows nothing about printers. If you ask her to fix one she'll throw an UnsupportedOperation exception (or a stapler). The compiler prevents you from getting in the habit of having your Secretary do other things.

Hope that made sense.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!