if a class Alpha has a method with arguments as public void foo(String... args)
& same method is tried to be overridden in a sub-class Beta by say public void foo(String a)
.And a reference object is created & instantiated to subclass Beta & trying to access foo method from Alpha. Its returning the value from Alpha class instead of the value from Beta Sub-class .
Shouldnt it return the value from BETA class as its initialized & assigned Beta class Object ?
What is the difference b/w Method(String ... args)
& Method(String a)
?
A method with 1 parameter of
String
does not override a method with 1 parameter ofString...
. The parameter typeString...
is a variable arity method, meaning 0 or more arguments can be passed, e.g.foo("one", "two", "three")
. In the body of the method, it is treated as an array, not a singleString
. If you had used@Override
inBeta
's declaration offoo
, the compiler would catch that you didn't overridefoo
. You have overloadedfoo
instead.To override a method, you must have the parameters and the name of the method match exactly. In fact, you can't even have the type be
String[]
, even if the parameters are both treated as arrays, due to how the method is called.Method overriding occurs when a subclass tries to implement a method with:
Method overloading occurs when more than 1 method uses the same method name but having different method signature. (Method overloading can occur within the same class, i.e. no sub-classing needed)
Method signature includes:
Excludes
PROOF
You can actually easily test what you asked by yourself:
The Output?
It will be an error. Because you are telling the Child class to override method
doWork(String)
from Parent. However such method cannot be found in the Parent class. The Parent class only has a method known asdoWork(String, String)
.Conclusion: Answer to you question is no, it will not be overridden since the method from the child class is having a different method signature with the parent class' method.
It's because the method in
Beta
does not override the one in Alpha because it does not have the same formal parameters.String...
is not the same asString
, much like the wayString[]
is not the same asString
.