Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overriding with different parameters

Lets say I have a parent class:

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

and it's child class:

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

Now the child has both methods with different parameters. This does method overloading. But I need method overriding, i.e, If someone tries to call aMethod() with the object of child class then the method of child class should be called or say method of parent class should not be accessible. But I can't change the access modifier of the parent class because the parent class has other children as well and they need the method as is.

So any suggestions?

like image 860
Charu Avatar asked Jul 13 '26 10:07

Charu


2 Answers

You can override the Parent's 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 the existing method of the Child class to be executed :

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

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

Either way Parent's implementation of aMethod() will never be executed for instances of class Child.

like image 69
Eran Avatar answered Jul 15 '26 22:07

Eran


this

void aMethod() {

and this

void aMethod(int number)

are totally different methods (their signature is different) so there is not way to say that aMethod(int number) is overriding aMethod()

so what you can do?:

override the only method you can and the OVERLOAD it

public class Child extends Parent {

    @Override
    public void aMethod() {
        // TODDY
    }

    //here overload it
    public void aMethod(int number){
        // TODDY
    }
}
like image 31
ΦXocę 웃 Пepeúpa ツ Avatar answered Jul 15 '26 22:07

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!