Search code examples
javamethodsencapsulationsettergetter

Set and Get Methods in java?


How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?


Solution

  • Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

    For example, for a member variable:

    Integer x;
    

    You might have methods:

    Integer getX(){ return x; }
    void setX(Integer x){ this.x = x; }
    

    chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.