Determine output:
class A{
public void method1(){
System.out.print("Class A method1");
}
}
class B extends A{
public void method2(){
System.out.print("Class B method2");
}
}
class C extends B{
public void method2(){
System.out.print("Class C method2");
}
public void method3(){
System.out.print("Class C method3");
}
}
public class Test{
public static void main(String args[]){
A a = new A();
C c = new C();
c.method2();
a = c;
a.method3();
}
}
class A{
public void method1(){
System.out.print("Class A method1");
}
}
class B extends A{
public void method2(){
System.out.print("Class B method2");
}
}
class C extends B{
public void method2(){
System.out.print("Class C method2");
}
public void method3(){
System.out.print("Class C method3");
}
}
public class Test{
public static void main(String args[]){
A a = new A();
C c = new C();
c.method2();
a = c;
a.method3();
}
}
A. Class B method2 Class C method3
B. Class C method2 Class C method3
C. Compilation Error
D. Runtime exception
E. None of these
Answer: Option C
Solution(By Examveda Team)
It is important to understand that it is the type of reference variable - not the type of the object that it refers to - that which determines what members can be accessed. That is, when a reference to a subclass object is assigned to a super class reference variable, we will have access only to those parts of the object defined by the superclass.
In the above program method method3() is defined in the class C which is a subclass of B and so A. Even the reference variable a refers to c, a can't access method3() as this method is unknown to class A.
A. The process of acquiring properties and behaviors of one class by another
B. The process of creating objects
C. The process of encapsulation
D. The process of overloading methods
In Java, which keyword is used to implement inheritance between classes?
A. inheritsFrom
B. inherits
C. implements
D. extends
A. The class that inherits properties and behaviors
B. The child class
C. The class that is inherited from
D. The class that is marked as "final"
In Java, can a subclass inherit constructors from its superclass?
A. Only if the subclass is marked as "final"
B. Yes, a subclass inherits constructors from its superclass
C. Only if the superclass is marked as "static"
D. Only if the subclass is marked as "final"
Join The Discussion