我总是想知道从 Java 中的类方法访问类属性的最佳方法。
您能否快速说服我以下 3 种解决方案中的哪一种(或完全不同的一种:P)是一种好习惯?
public class Test {
String a;
public String getA(){
return this.a;
}
public setA(String a){
this.a = a;
}
// Using Getter
public void display(){
// Solution 1
System.out.println(this.a);
// Solution 2
System.out.println(getA());
// Solution 3
System.out.println(this.getA());
}
// Using Setter
public void myMethod(String b, String c){
// Solution 1
this.a = b + c;
// Solution 2
setA(b + c);
// Solution 3
this.setA(b + c);
}
}