What is displayed when the following code is executed?
class Parent
{
private void method1()
{
System.out.println("Parent's method1()");
}
public void method2()
{
System.out.println("Parent's method2()");
method1();
}
}
class Child extends Parent
{
public void method1()
{
System.out.println("Child's method1()");
}
public static void main(String args[])
{
Parent p = new Child();
p.method2();
}
}
Choices
A. Compile-time error
B. Run-time error
C. Prints:
Parent's method2()
Parent's method1()
D. Prints:
Parent's method2()
Child's method1()
Correct choice:
C
Explanation:
Choice C is the correct answer.
The code will compile and run without error. The variable p refers to the Child class object. The statement p.method2() on execution will first look for method2() in the Child class. Since there is no method2() in the child class, the method2() of Parent class will be invoked, which will result in "Parent's method2()" being printed.
Note that from the method2(), there is a call to method1(). Because method1() of the Parent class is private, it will be invoked. Had method1() of the Parent class been public, protected, or friendly (default), the Child's method would have been called.
Source: Whizlabs Java Certification (SCJP 1.4) Preparation Kit. Whizlabs Software was co-founded by the author of this article.
Return to article |