23 February 2009

package protected methods java puzzler

An excellent Java puzzler

comments by xeukun JOU

package m1;
public class M1 {
     void doIt() {System.out.println("M1");}

package m1;
public class M2 extends M1 {
    void doIt() {System.out.println("M2");}

package m2;
public class M3 extends M2 {
    void doIt() {System.out.println("M3");}

package m1;
public static void main(String[] args) {
     M1 m=new M3();

This will show "M2", not M3, even though M3's doIt() should be invoked, based on what a vtable would indicate.

It's not a common thing; I wouldn't have put main() in the m1 package, and if it's not local to M1 you won't see the behavior (it won't compile). But it's still an interesting corner case, and I think it's not obvious unless you've run into it.

No comments:

Post a Comment