How does value of (String… args) affect in subclas

2019-03-02 08:46发布

问题:

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)?

回答1:

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 as String, much like the way String[] is not the same as String.



回答2:

A method with 1 parameter of String does not override a method with 1 parameter of String.... The parameter type String... 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 single String. If you had used @Override in Beta's declaration of foo, the compiler would catch that you didn't override foo. You have overloaded foo 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.



回答3:

Method overriding occurs when a subclass tries to implement a method with:

  • same method signature as the method in the parent class

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:

  • Method name
  • Method parameter list

Excludes

  • Method return type
  • Access modifiers (public/protected/private)
  • Other modifiers (final/static/etc..)

PROOF

You can actually easily test what you asked by yourself:

class Parent{
    public void doWork(String s1, String s2){
        System.out.println("From Parent");
    }
}

class Child extends Parent{
    @Override   //<-This will tell you whether it successfully overridden or not
    public void doWork(String s1){
        System.out.println("From Child");
    }
}

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 as doWork(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.