Good design: How use fields of superclass

Possible Duplicate:
Java protected fields vs public getters

If i have that class B extends A and in A i have some fields that i use also in B, it's better make this fields protected and call them from class B or write getter methods for this fields and so use this method from class B ? (this fields are setted in constuctor of A)


If you prefer getters to public member data in your public interface (as you should), then use protected getters for the same reason. Subclasses, like public clients, are classes outside your control which don't need unfettered access to your internals.


I think using getter and setter methods is always the better choice, even in the same class! The reason for this is quite simple. Imaging that you want to change anything in the way you access the field.

For example you access an int that holds a value. Now for some reasons you want to multiply this value always by 2 before accessing them. If you use accessor methods you simple change your method:

private int test = 5;

public int getValue() {
   return test;
}

to

public int getValue() {
   return test * 2;
}

If you want to the same when you directly access the field test, you have big problems when you want to change such things.


In my opinion, and I know many would disagree, if the classes are all implemented by you, it's better to use protected objects / variables, since it gives you more control over the internals of the class extending the superclass. And I wouldn't worry too much about encapsulation, because you control the whole source.

If the classes are to be extended by someone else who won't have the source of the class, I would recommend using getters if it's necessary, and even avoid this when possible.

链接地址: http://www.djcxy.com/p/51536.html

上一篇: 使用PHP来触发另一个PHP脚本,然后忽略

下一篇: 好的设计:如何使用超类的领域