Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can any one explain me this

 
SRI PARUCHURI
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following classes defined in separate files, what will be the effect of compiling and running this class Test?
code
class Vehicle {
public void drive() {
System.out.println("Vehicle: drive");
}
}
class Car extends Vehicle {
public void drive() {
System.out.println("Car: drive");
}
}
public class Test {
public static void main (String args []) {
Vehicle v;
Car c;
v = new Vehicle();
c = new Car();
v.drive();
c.drive();
v = c;
v.drive();
}
}
endCode
a)Generates a Compiler error on the statement v= c;
b)Generates runtime error on the statement v= c;
c)Prints out:
list
Vehicle: drive
Car: drive
Car: drive
endList
d)Prints out:
list
Vehicle: drive
Car: drive
Vehicle: drive
endList
answer
c
How 'c' will be correct.
Thanks,
Sri
 
Kathy Rogers
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important thing to remember when faced with a question like this is:-
At runtime, the JVM knows what type of object it's dealing with and uses the object's class to determine which method to run.
So we create a new vehicle - it's definitely a vehicle - we call vehicle's constructor directly to create it.
We create a Car object - it's definitely a Car - we call car's constructor to create it.
So we call v.drive() - v is a Vehicle so we get
Vehicle: drive
We call c.drive() - c is definitely a car so we get
Car: drive
That's quite straight forward. What happens next is that assignment:-
v = c;
That's fine because Car is a subclass of Vehicle so you can treat a Car object as a vehicle. But even though it's referred to using v, the object remains a Car object. So v is a label that refers to a Car object. At runtime, the JVM works out that v, even though it might superficially appear to be a Vehicle, is really a Car object so it calls Car's drive method so the last line output is
Car: drive.
If you want a clearer practical illustration of this, try running this Test file with the existing Vehicle and Car classes:-

Even though v looks like a Vehicle, you creating a Car object.
Hope this helps.
Kathy

[This message has been edited by Kathy Rogers (edited January 02, 2001).]
 
SRI PARUCHURI
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Kathy,
Sri
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic