16

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.

4

7 回答 7

14

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
}
于 2013-01-11T05:08:24.647 回答
10

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.

于 2013-01-11T05:09:25.470 回答
2

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.

于 2013-01-11T05:09:36.687 回答
2

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.

于 2013-01-11T05:09:55.373 回答
1

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.

于 2013-01-11T05:12:22.923 回答
0

one way to do it may be to use virtual keyword instead of abstract but it doesnt require to override, but you can do override. though so, you can instantiate.

another way and more recommended is to create an interface where you can indicate what the class requirements. it is something like abstract, you indicate what to require, but keep in mind interface is not a class. it's more like pointer. for more for interface click: https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

于 2016-01-17T04:37:30.190 回答
0

So, java.lang.Thread is a concrete class that implements the Runnable interface. Therefore, it must be that Thread implements a public void run() method. Yet, when you extend Thread, like MyClass extends Thread { }, you are required to implement the run() method.

It stands to reason that there is a way to force overriding of a method without making the containing class abstract.

于 2021-02-28T01:29:43.263 回答