Java – method of overriding with different parameters

Suppose I have a parent class:

class Parent{
    public void aMethod() {
        //Some stuff
    }
}

It is a children's class:

class Child extends Parent {
    public void aMethod(int number){
        //Some other stuff
    }
}

Now, children have two methods with different parameters This overloads the method But I need method override, that is, if someone tries to call amethod () with a subclass object, the subclass method should be called or the parent method should not be accessed But I can't change the access modifier of the parent class, because the parent class also has other children, and they need the same method

Do you have any suggestions?

Solution

You can override the parent method in the child class and throw an exception:

class Child extends Parent {
    public void aMethod(int number){
        //Some other stuff
    }

    @Override
    public void aMethod() {
        throw new UnsupportedOperationException();
    }
}

Or, if you want to execute an existing method of the child class:

class Child extends Parent {
    public void aMethod(int number){
        //Some other stuff
    }

    @Override
    public void aMethod() {
        aMethod (someIntValue);
    }
}

Either way, the parent's amethod () implementation will never be executed for instances of class child

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>