I have below classes:
public abstract class Parent {
public abstract boolean checkName(String str);
}
public class Child1 extends Parent {
public static final String NAME = "CHILD1";
@Override
public boolean checkName(String str) {
//check input validity:
if (!NAME.equals(str)) {
throw new IllegalArgumentException("some thing");
}
//...
}
}
public class Child2 extends Parent {
public static final String NAME = "CHILD2";
@Override
public boolean checkName(String str) {
//check input validity:
if (!NAME.equals(str)) {
throw new IllegalArgumentException("some thing");
}
// ...
}
}
You can see check input validity
parts of checkName
methods in both classes are same.I know there is no way to move this joint part to abstract checkName
method of parent,but is there a way to avoid this repeating?
You might switch things around so that the
checkName()
function is concrete in theParent
class, have it do the input validity check, then invoke some abstract method that your child classes implement to do the rest of the processing.