Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require override of specific methods of a non-abstract class

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.

like image 826
brain56 Avatar asked Jan 11 '13 05:01

brain56


People also ask

Can you override non-abstract method?

"Is it a good practice in Java to override a non-abstract method?" Yes.

Can you override non-abstract class?

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.

How can we override abstract method in non-abstract class?

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.

Do I have to override abstract method from abstract class in non-abstract class in case of inheritance?

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.


2 Answers

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
}
like image 92
EJK Avatar answered Oct 03 '22 04:10

EJK


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.

like image 28
Thilo Avatar answered Oct 03 '22 03:10

Thilo