Reputation: 1075
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?
Upvotes: 3
Views: 6702
Reputation: 393771
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
.
Upvotes: 5
Reputation: 48258
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
}
}
Upvotes: 3
Reputation: 12751
You can implement a version of aMethod
in the Child class and it will be called instead of the parent's version when you call that method on any instance of the Child class.
You don't need to change the Parent's signature to override the method because both public and protected methods can be overridden.
class Child extends Parent {
@Override
public void aMethod() {
// TODO
}
public void aMethod(int number){
//Some other stuff
}
}
Upvotes: 1