Java is the future !: Quiz of the Day | Oct 28, 2010

Thursday, October 28, 2010

Quiz of the Day | Oct 28, 2010

Given the following two classes, which statement is true?

Choose one answer. 
a. The code will compile and run only if line 5 is removed. 
b. The code will compile and run only if line 6 is removed 
c. The code compiles and runs, printing "Test" twice. 
d. The code compiles but throws an exception at runtime.


Solution : Choice B is the correct answer.

The code will compile and run only if line 6 is removed. 

Subclasses that are in a package different from that of the superclass can access protected members of the superclass only through inheritance. Such a subclass cannot use a superclass reference to access a protected member.

Line 5 is legal since we are invoking the test() method using the subclass reference itself, it is the inherited method which we are accessing.

However, line 6 will not compile because the subclass is using the superclass reference to call the test() method.

Since the code does not compile, choices C and D are incorrect.

Reference:
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html


Source : "Facebook community"

No comments:

Post a Comment