• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

need reply

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
swarna kumar
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks valentin,
good explanation, i thought the answer is d.
swarna
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic