As others already said, your given example would benefit from varargs. But that's just one example, and is completely outside of any OOP discussion.
In my view, overloading has nothing to do with OOP. It's just some independent methods that accidentally got the same name. Luckily, they have different parameter lists, so the compiler is able to guess which one you meant. Having instead methods with different names gives exactly the same results (and without the potential ambiguities introduced by overloading). It's just more reader-friendly to always see e.g. sum(...)
instead of sumIntInt(...)
or sumIntIntInt(...)
.
On the other hand, OOP polymorphism means that the method to be used is decided at runtime, depending on the runtime type of some instance involved in the call. In Java, it's only the instance "before the dot" that gets that treatment. The various classes that can be passed into the call may each have their own implementation of the method, and that's called overriding.
So, whenever you want to make some behaviour dependent on some instance class, make it a method of the relevant class tree.
If you were to apply that pattern to your example, you'd e.g. have to create some (contrived) classes/interfaces:
SomeIntegers
as an interface with a method sum()
,
TwoIntegers
implementing SomeIntegers
, with fields a
and b
and a sum()
method adding those two numbers,
ThreeIntegers
implementing SomeIntegers
, with fields a
, b
, and c
and a sum()
method adding those three numbers.
Then you'd use code following the pattern:
SomeIntegers someInts = ...;
int result = someInts.sum();
Depending on the concrete class of the someInts
instance, you'd get the appropriate addition implementation.
Of course, this is a quite contrived example, but maybe it helps to get the idea.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…