I had a function in Java with method signature
public void myMethod (int someInt, String someString)
in my abstract class and I had over-ridden it with method
public void myMethod (Integer someInt, String someString)
The over ride does not work. Is this an inconsistency ? I thought auto-boxing applied to method signature over-ride as well.
No. It gives compile time error. Compiler treats int and Integer as two different types while overriding.
A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
The getFact() method is a new method declared in this FactBook class (it's not a method of the Object class), so you do not need to override it. To have a list of all the methods your class inherits, just call Ctrl+O in Android Studio.
@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
int
and Integer
are two different types. Autoboxing blurs the distinction at the source code level for the convenience of programmers, but does not change the fact that they are in fact two very different types.
As such, you can not @Override
a method that takes an int
with one that takes an Integer
and vice versa.
Note that you should probably think twice before declaring a method to take an Integer
instead of an int
. Here's an excerpt from Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives:
In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the
==
operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throwNullPointerException
. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.
int num = Integer.getInteger("123")
throw NullPointerException
? (!!!)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With