Reputation: 2887
I’ve method which I inherit from the base class.
I’ve 5 class that inherit the method and override it but doing the same,
Now I need to change all the methods to support additional scenario according to envoriment variable
//specific implications
@Override
protected boolean prepareDirectory(Configuration configuration, Logger logger) throws Exception
//logic here as before
if(env===“global”) {
//do something
}
}
Of course I can do this if inside all the class which works but there is a better approach to overcome this.
Since all the 5 class should use the same logic inside the new if
.
Upvotes: 0
Views: 65
Reputation: 1219
You can do that by a Base class that does the common logic of your five classes, and, at the same time, gives the possibility to each one of them to do their specific logics :
abstract class Base {
public RETURN_TYPE commonLogic(SOME_PARAMS){
//common logic goes here
}
public abstract RETURN_TYPE specificLogic(SOME_PARAMS);
}
and then inherit this Base class, implement the specific logic :
class Logic1 extends Base{
@Override
public RETURN_TYPE specificLogic(SOME_PARAMS){
// your specific logic
}
}
Upvotes: 1
Reputation: 283
If you are working with Java 8, you should use Interface with a default method.
Create an Interface and then create one method with default access modifier, it would be the best approach.
Upvotes: 1
Reputation: 37584
You can achieve it with an abstract method. Something like
abstract class BaseClass {
abstract void basePrepare(Configuration configuration, Logger logger);
protected boolean prepareDirectory(Configuration configuration, Logger logger) throws Exception {
if (/* condition */) {
basePrepare(configuration, logger); // implementing class does his stuff
}
}
}
Upvotes: 2