Java: creating an abstract method for each extending class
Is there any keyword or design pattern for this?
Check the update
public abstract class Root
{
public abstract void foo();
}
public abstract class SubClass extends Root
{
public void foo()
{
// Do something
//---------------- Update -------------------//
// This method contains important code
// that is needed when I'm using a instance
// of SubClass and it is no instance of any
// other class extending SubClass
}
}
public class SubberClass extends SubClass
{
// Here is it not necessary to override foo()
// So is there a way to make this necessary?
// A way to obligate the developer make again the override
}
thanks
a source to share
If you are doing this, you are probably overusing inheritance; Inheritance, contrary to popular myth, is not intended to create custom interceptors / handlers, but rather to provide alternative implementations.
If you want your user to provide some kind of / hook / callback function, you should define an interface that only exposes the methods that you need to define for your users. Then you have to require the user to pass an instance of that interface to your object constructor or pass it to the function they want.
Aggregation, delegation, and composition are often better and safer design patterns than inheritance; forcing other users to inherit from your class is incredibly risky, as it provides the user with many opportunities to violate the contract of your class, or to invalidate your base class invariant.
a source to share
You cannot have it both ways. You cannot provide a method with a default implementation AND require that child classes override it. Instead of declaring a method as abstract in Root, you can define an interface (IFoo) with the declared method, and then provide an abstract class that implements the interface. This will still require a specific child class, but it doesn't require method overriding.
Most of the time you see this type of template, the interface is used to define a set of methods, and the abstract base class provides some default implementations for some, but not all, of the methods from the interface. This requires that a specific child class provide code for the rest of the methods and the ability to override the default behavior.
In any case, you cannot provide default behavior for a single method and require child classes to override the same method.
a source to share