當你希望你的代碼是可讀的,並且避免公共類的字段可以從另一個類以錯誤的方式使用時,getter和setter很有用。 這個例子顯示瞭如何是重要的。
CLASS A:
public class ClassA{
// in the body class
private String fieldClass1;
//classic setter
public void setfieldClass1(String f1)
{
fieldClass1 = f1;
}
}
B類:
public class ClassB{
// in the bodyclass
public String fieldClass2;
//classic setter
public void setfieldClass2(String f2)
{
setfieldClass2 = f2;
}
CLASS C:
public class ClassC{
//in the body of the class this method use class a and class b
public void calc()
{
ClassA aObject = new ClassA();
ClassB bObject = new ClassB();
ClassA.fieldClass1 = 5 + 5; // illegal expression for the compiler and costrain the developer to use setters
ClassB.fieldClass2 = 8 + 8; // legal expression
}
}
這意味着必須定義一個 「改性劑邏輯」 (受保護的,私人的,公共的c)在製造者和獲得者之前。在修飾符之前和定義setters和getters之後定義。
倆!添加你的方法並添加一個通用的setter方法 – 2015-04-01 21:48:52