Vidyalelo
Java Programming · Q38

Inheritence

Programming · Java Programming · question 38

Q38

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();

A.
Class B method2 Class C method3
B.
Class C method2 Class C method3
C.
Compilation Error
Answer
D.
Runtime exception
E.
None of these

Answer: Option C

Solution

Answer: Option C
Solution:

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.