Method Overriding and Autoboxing
Java is full of little nuances. One interesting is the handling of overridden methods and the auto-boxing feature that was introduced in Java 1.5. For example suppose you had a class with the following methods..
public void doStuff(long myParam) { System.out.println("long"); } public void doStuff(Integer myParam) { System.out.println("Integer"); }
Now take the following code block
int myInt = 4; doStuff(myInt); doStuff(3);
What would be output? The answer is...
long
long
Why is this? Well one might thing that Java will take myInt and automatically box it to be an Integer then call the method that accepts an Integer parameter. This is not the case. When autoboxing was introduced in Java 1.5 the designers wanted to make absolutely sure that legacy code (previous to Java 1.5) would still work as it always has. To guarantee this they had to make implicit casting favored over auto-boxing when overriding methods.
No comments:
Post a Comment