Require override of specific methods of a non-abstract class
Solution 1
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.
Solution 2
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
}
Solution 3
I don't think you do exactly what you want. Alternatively, create MyBaseClass as an abstract class with methodC()
abstract implementations for methodA()
and methodB(). Derive MyClass from it, adding an implementation for methodC()
. Any classes that you do not want to have inherit that implementation should directly subclass MyBaseClass rather than MyClass.
Solution 4
If you want a method to be just inherited use final
keyword. To force overriding make it abstract
. However, only non-abstract child classes will have to override it.
Solution 5
AFAIK there is no way to force override a method in Java with out abstract.
You can achive with abstract
class by making the method as abstract
method.
![brain56](https://i.stack.imgur.com/J1BnY.jpg?s=256&g=1)
Comments
-
brain56 about 2 years
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 inheritmethodA()
andmethodB()
?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.
-
brain56 over 11 yearsIt is specified in the question that the class must be non-abstract.
-
EJK over 11 yearsYes, and in the question, you stated that "if it is not possible can you propose an alternative solution"?
-
hansvb over 11 yearsThe question also does not give any background or motivation as to why it must be non-abstract.
-
brain56 over 11 yearsOK, I see your point now. It's just that the answer wasn't provided clearly. I thought you were another one of those who don't read the question well. Sorry, I withdraw my downvote.
-
msysmilu over 9 yearsOP edit: I need a non-abstract class because I want to be able to instantiate this class too.
-
Slobodan Pejic over 7 yearsJava does not have a virtual keyword, and methods are virtual by default. The
final
keyword makes methods non-virtual.