• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Himai Minh
  • Carey Brown
  • salvin francis

need reply

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
thanks valentin,
good explanation, i thought the answer is d.
swarna
 
Mo-om! You're embarassing me! Can you just read a tiny ad like a normal person?
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic