What is a good practice to access class attributes in class methods?
- by Clem
I always wonder about the best way to access a class attribute from a class method in Java.
Could you quickly convince me about which one of the 3 solutions below (or a totally different one :P) is a good practice?
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);
}
}