Saturday, August 28, 2010

Compilation failure if overriding method has weaker access modifier

Courtesy of Sun Web Learning Center


Given:

 6. class Bird {
 7.   protected void talk() { System.out.print("chirp "); }
 8. }
 9. public class Macaw extends Bird {
10.   public static void main(String [] args) {
11.     Bird [] birds = {new Bird(), new Macaw()};
12.     for( Bird b : birds)
13.       b.talk();
14.   }
15.   void talk() { System.out.print("hello "); }
16. }

What is the result?


A chirp chirp
B chirp hello
C hello hello
D hello chirp
E Compilation fails
F An exception is thrown at runtime

E is correct. The overriding talk() method has a weaker access modifier.

No comments:

Post a Comment