# Wednesday, 16 July 2014
« Java Security Fixes | Main | New Development Snapshot »
Java Method Overriding Is FUBAR Part 10 of ∞

Yesterday's JDK 7u65 and 8u11 updates changed method overriding yet again and, of course, it is still broken.

Take this example:

package pkg1;

public class A {
  { foo(); }
  void foo() { System.out.println("A.foo"); }
}

package pkg2;

public class B extends pkg1.A {
  { foo(); }
  void foo() { System.out.println("B.foo"); }
}

package pkg1;

public class C extends pkg2.B {
  { foo(); }
  void foo() { System.out.println("C.foo"); }
}

package pkg2;

public class D extends pkg1.C {
  { foo(); }
  void foo() { System.out.println("D.foo"); }
}

public class test {
  public static void main(String[] args) {
    new pkg2.D();
  }
}

Running this with JDK 8u5 yields:

D.foo
D.foo
D.foo
D.foo

Which is, of course, wrong. In yesterday's updates they tried to fix this, but only partially succeeded:

D.foo
D.foo
C.foo
D.foo

The sensible output would be:

C.foo
D.foo
C.foo
D.foo

Wednesday, 16 July 2014 13:27:41 (W. Europe Daylight Time, UTC+02:00)  #    Comments [2]
Wednesday, 16 July 2014 14:35:05 (W. Europe Daylight Time, UTC+02:00)
Could you give a justification for the sensible output? As it is you've just put it out there without any rhyme or reason and the less enlightened of us are just supposed to take it as written that it's correct... :)
Wednesday, 16 July 2014 14:39:13 (W. Europe Daylight Time, UTC+02:00)
Package private methods should only override package private methods in the same package. So C.foo should override A.foo and D.foo should override B.foo and nothing else. This is IMO the sensible behavior and also what the JVM spec says.
Jeroen Frijters
Name
E-mail
Home page

I apologize for the lameness of this, but the comment spam was driving me nuts. In order to be able to post a comment, you need to answer a simple question. Hopefully this question is easy enough not to annoy serious commenters, but hard enough to keep the spammers away.

Anti-Spam Question: What method on java.lang.System returns an object's original hashcode (i.e. the one that would be returned by java.lang.Object.hashCode() if it wasn't overridden)? (case is significant)

Answer:  
Comment (HTML not allowed)  

Live Comment Preview