In details. In this question i've used simple example. But in real life, there is huge logic in methods with difference in one state variable only. Example. I have two classes which have method with the same logic. Difference between these two classes is in class variable which used in method.
class A {
private String str = "A";
void method() {
System.out.print(str);
}
}
class B {
private String str = "B";
void method() {
System.out.print(str);
}
}
I suppose using inheritance i can achieve the result.
abstract class Abs {
void method() {
System.out.print(getStr());
}
abstract String getStr();
}
class A extends Abs {
String getStr() {
return "A";
}
}
class B extends Abs {
String getStr() {
return "B";
}
}
Is it good solution? Or there are any others, or maybe design-patterns to achieve my goal? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire