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?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With