The father class is not and cannot be made abstract. The method to overload is protected so interfaces cannot be used there.
Having these two restrictions in mind is it possible to do it?
You can't force the method to be overridden - that's what abstract methods are for (which you've stated isn't an option).
One possibility is to make the method in the base class throw an UnsupportedOperationException
. Then, the subclass must override it in order to prevent the error being thrown. That way, you can at least detect if the method has been overridden.
For example:
public class Father {
public void method ( ) {
throw new UnsupportedOperationException( );
}
}
public class Child1 extends Father {
}
public class Child2 extends Father {
public void method ( ) {
// Do something useful here...
}
}
Calling Child1.method()
will throw UnsupportedOperationException
, indicating that it hasn't overridden Father
's method()
. Calling Child2.method()
will not throw the exception, meaning that it has overridden method()
.
You could throw an UnsupportedOperationException from the parent. That won't help at compile time but will at run time.
Since abstract is not an option you could have the method throw a NotImplementedException
. This is a more explicit exception then UnsuppotedOperationException
.
Note: This will not prevent the code from compiling and will only throw an exception at run time.
Public Clazz {
public void methodToOverride(){
Throw new NotImplementedException();
}
}
Some Examples implemntations:
Apache
Sun
sharkysoft.com
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