aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need reply Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "need reply" Watch "need reply" New topic
Author

need reply

swarna kumar
Greenhorn

Joined: Nov 11, 2001
Posts: 17
hai friends,
iam new member of this group, iam going to write the exam very soon,i need the result as soon as possible,pls
i got this question in 4test mock exam,
Given the following classes defined in separate files:
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();
}
}
What will be the effect of compiling and running this class Test?

Generates a Compiler error on the statement v= c
Generates runtime error on the statement v= c
Prints out:
Vehicle : drive
Car : drive
Car : drive
Prints out:
Vehicle : drive
Car : drive
Vehicle : drive
anyone can explain how it works,
thx
swarna
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
The third option is correct, it prints out
Vehicle : drive
Car : drive
Car : drive
The reason is that v=c is perfectly correct since you can reference an object of any class with a variable whose type is the superclass of the reference object, here vehicle is a superclass of Car. You cannot do the opposite, though.
The last is also wrong. v=c has the effect of making the variable v of Type Vehicle point to c an instance of Car.
Then when you invoke drive() upon v, method drive() of Car is actually invoked (late binding)
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
swarna kumar
Greenhorn

Joined: Nov 11, 2001
Posts: 17
thanks valentin,
good explanation, i thought the answer is d.
swarna
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: need reply
 
Similar Threads
superclass and subclass
answre this problem
Hi
object ref types trip me up all the time
Can any one explain me this