int does not override Integer in Java

后端 未结 6 944
春和景丽
春和景丽 2020-12-11 02:23

I had a function in Java with method signature

public void myMethod (int someInt, String someString) 

in my abstract class and I had over-

6条回答
  •  孤街浪徒
    2020-12-11 03:23

    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 throw NullPointerException. 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.

    See also

    • Java Language Guide/Autoboxing

    Related questions

    • What is the difference between an int and an Integer in Java/C#?
    • Is it guaranteed that new Integer(i) == i in Java? (YES!!! The box is unboxed, not other way around!)
    • Why does int num = Integer.getInteger("123") throw NullPointerException? (!!!)
    • Why null == 0 throws NullPointerException in Java?

提交回复
热议问题