What is a good practice to access class attributes in class methods?

Posted by Clem on Stack Overflow See other posts from Stack Overflow or by Clem
Published on 2010-04-20T21:22:31Z Indexed on 2010/04/20 21:33 UTC
Read the original article Hit count: 212

Filed under:
|
|
|

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);
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices