Is it possible to have a class defined like
public class MyClass
{
public void methodA(){} // Inherit
public void methodB(){} // Inherit
public void methodC(){} // Require override
}
and then have all classes which extend from MyClass to be required to override methodC()
but just simply inherit methodA()
and methodB()
?
If it is possible, how does one do it? If it's not possible, can you propose an alternative solution to achieve a similar result?
EDIT:
I need a non-abstract class because I want to be able to instantiate this class too.
"Is it a good practice in Java to override a non-abstract method?" Yes.
An abstract class can have a mixture of abstract and non-abstract methods. Subclasses of an abstract class must implement (override) all abstract methods of its abstract superclass. The non-abstract methods of the superclass are just inherited as they are. They can also be overridden, if needed.
A non-abstract child class of an abstract parent class must override each of the abstract methods of its parent. A non-abstract child must override each abstract method inherited from its parent by defining a method with the same signature and same return type. Objects of the child class will include this method.
An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding, the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it.
You would have to make your base class abstract.
public abstract class MyClass
{
public void methodA(){} // Inherit
public void methodB(){} // Inherit
public abstract void methodC(); // Require override
}
You cannot require an override of a non-abstract method.
Maybe you can do something similar to the template method pattern:
public final void methodC() { methodC1(); someMoreLogic(); methodC2();}
protected abstract void methodC1();
protected abstract void methodC2();
Here methodC encapsulates a fixed algorithm that calls into pieces that have to be supplied by the subclasses.
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