Marc, himself, his blogs, and you reading them.
Upon general request, another Java mind-puzzle. Try to predict what this one does:
14 public class Main2 {
15
16 public static void main(String[] args) {
17 TestImpl ti = new TestImpl();
18 ti.act("Me");
19 ((Test)ti).act("You");
20 ((Testje)ti).act("Him");
21 }
22 }
23
24 interface Test {
25 public void act(Object o);
26 }
27
28 class Testje {
29 public void act(String s){
30 System.out.println("String - Base: " + s);
31 }
32 }
33
34 class TestImpl extends Testje implements Test {
35 public void act(Object o){
36 System.out.println("Object: " + o);
37 }
38 public void act(String s){
39 System.out.println("String: " + s);
40 }
41 }
Did you predict this?
String: Me
Object: You
String: Him
If you did, then you are aware that overloading in Java is resolved at compile-time, while the run-time late-binding kicks in (only) in cases of inheritance.
There again is a fair amount of astonishment in this case, so I'ld like the setup be avoided, however I'm still doubthing on how to translate this knowledge into some general advice. Currently at:
Do not introduce overloaded versions for methods imposed on you by the interfaces you implement. You should in stead consider putting the overloaded version inside the interface itself. See it as ownership: the interface introducing a method name claims all rights on that used name.
This one bit me a long time ago, I just happened to remember while blogging the other one down... kind of trauma triggered memory :-)
By the way: tomk was so kind to point out that Effective Java has much more of these listed. My current Java must-read is the ever dull (but so right, and complete) Java Rules.
# Posted by mpo at 11:32 PM | TrackBack
