简体   繁体   中英

Must I use a getter method inside of my own class in Java?

Say I have some class:

public class A {
    private int val = 0;

    public int getVal() {
        return val;
    }

    public void addFrom(A otherA) {
        this.val += otherA.val;
        if (otherA.val > 0)
            otherA.val = 0;
        else
            otherA = Math.abs(otherA.val);
    }
}

Should I be using getter methods instead to use otherA's val variable? Is it better style to do so?

Edit: This is a very simplified version of a class that takes much too long to read. But assume that there IS lazy initialization going on, that there are other methods that access this class, etc. I have updated the example method so that this may be more clear, but I hope it is clear that my question involves accessing the other object's variables, and want to know if it is faux pas to use a direct variable access for something that is not "this".

No, absolutely not.

You should use the variable directly when you're inside the class' members, and use getters in every other situation (when you would get an error because val is private anyway).

public int getVal() is intended to present your gift(variable) within a box to the outside world (encapsulation). Do you give gifts yourself in a box? It's weird, so use the variable as it is.

You can use variables, but the current code does not compile. Probably, the return should be int instead of boolean.

Probably, your intention is to override the compareTo method from the Comparable interface

Adding an unnecessary getter reveals internal structure and this is an opportunity for increased coupling.

A truly well-encapsulated class has no setters and preferably no getters either. Rather than asking a class for some data and then compute something with it, the class should be responsible to compute something with its data and then return the result.

Use of accessors to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added for field where they're really required. A class should expose larger behavior which happens to use its state, rather than a repository of state to be manipulated by other classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM