Search code examples
javagetter-setterprivate-members

Why do we make variables private where we can access them using getter and setter?


I am not able to understand the concept of making variables private as we can access them outside the class using getter and setter methods.

So how these private variable remain private.


Solution

  • In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for name:

    class Dummy
    {
    private String name;
    
    public void Dummy() {}
    
    public void Dummy(String name) {
        this.name = name;
    }
    
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    }
    

    The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

    Also, Declaring instance variables private is required so that different parts of the program cannot access them directly or modify them by mistake which could result in disaster in real world programs.

    Consider reading Why Use Getters and Setters?