Reputation: 13501
I'm not that good OO design .. so please bear with me..
I have Class A, And 2 classes which extend A. But both of them have same fields.. So what is better, to have getter / setters in A or to have same getter / setters in both child classes.. Or is there a better a way to do this..?
this is what i have done (mock)..
class A{
private int x;
protected A(int x){
this.x = x;
}
public static A createA(id a, int x){
switch(a){
case 0:
return new C(x);
break;
//so on
}
public int getX(){
return x;
}
}
Thanks..
Upvotes: 0
Views: 962
Reputation: 29213
Let's say your classes are A
(the parent) and B
and C
(the children). You say that B
and C
have some fields that are the same.
Ask yourself: If you had another class D
, child of A
, would it have those fields too regardless of its specific functionality?
If the answer is yes, then the existence of these fields in both subclasses is definitely not a coincidence, so you should probably define them in A
, because it means that they have these members precisely because they inherit from A
.
If the answer is no, the existence of these fields in the subclasses may or may not be a coincidence. So, you should ask yourself: Even if D
doesn't have these fields, does their existence in both B
and C
look more than just a coincidence? Do these classes share something that D
, another child of A
, simply doesn't happen to share?
If yes, then consider a new class E
that extends A
, with E
defining these common members and then make B
and C
children of E
instead of A
.
If not (if it looks to you like just a coincidence), then leave your structure as it is. Or consider an interface instead.
Upvotes: 1
Reputation: 1331
This depends on the classes
If those properties are a property of A then yes, if it's just chance they have the same properties then no.
Basicly the question you need to ask yourself is, will there ever be a class that extends A that doesn't need those properties.
If the answer is no, put them on A,
If the answer is yes, keep them on the sub-classes, or create another abstract class in between those 2 subclasses, having these 2 properties.
Upvotes: 2