*
The moose likes Beginning Java and the fly likes Can any one explain me this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can any one explain me this" Watch "Can any one explain me this" New topic
Author

Can any one explain me this

SRI PARUCHURI
Greenhorn

Joined: Dec 17, 2000
Posts: 15
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

Joined: Aug 04, 2000
Posts: 103
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

Joined: Dec 17, 2000
Posts: 15
Thanks Kathy,
Sri
 
 
subject: Can any one explain me this