What will be the result of compiling and executing the following program code?
class Vehicle{
public void printSound(){
System.out.print("vehicle");
}
}
class Car extends Vehicle{
public void printSound(){
System.out.print("car");
}
}
class Bike extends Vehicle{
public void printSound(){
System.out.print("bike");
}
}
public class Test{
public static void main(String[] args){
Vehicle v = new Car();
Bike b = (Bike) v;
v.printSound();
b.printSound();
}
}
class Vehicle{
public void printSound(){
System.out.print("vehicle");
}
}
class Car extends Vehicle{
public void printSound(){
System.out.print("car");
}
}
class Bike extends Vehicle{
public void printSound(){
System.out.print("bike");
}
}
public class Test{
public static void main(String[] args){
Vehicle v = new Car();
Bike b = (Bike) v;
v.printSound();
b.printSound();
}
}
A. Compilation fails.
B. ClassCastException exception is thrown at runtime.
C. "vehiclecar" is printed.
D. "vehiclebike" is printed.
E. "carcar" is printed.
Answer: Option B
Object of child class some of parent class is called inheritance.
you have done mistake
vehicle v = new Bike();
This is the answer
Inheritance define as object of child class acquire all the properties of parent class . It syntax is extends
for example :
class A extends B
Using interface it is a blue print of class it syntax is implements.
for example
class A implements B