Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaAdvantages of getter and setter Over Public Fields in Java with Examples

Advantages of getter and setter Over Public Fields in Java with Examples

Providing getter and setter methods to access any class field in Java can at first look pointless and meaningless, simply because you can make the field public, and it is available in Java programs from anywhere. In reality, many programmers do this in the early days, but once you start thinking in terms of enterprise application or production code, you can begin to see how much maintenance trouble it can make.

Since software spends more time on maintenance than development according to the SDLC process, it is worth having ease of maintenance as one of the development goals. One of the Java coding best practices involves simply using the getter and setter approaches in Java.

Below are some advantages of getter and setter over public fields

1.  The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.

2. You make the class accessible with many open source libraries and modules such as display tags by making fields private by including getter and setter and following the java bean naming convention. It uses a combination of reflection and the Java bean naming convention to load and access fields dynamically.

3. You give Subclass an opportunity to override this method with getter and setter and return what makes more sense in the context of the subclass.

4. Hiding the property’s internal representation by using an alternative representation to expose a property.

5. Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.

Java




class Person {
    // private = restricted access
    private String name;
  
    // Getter
    public String getName() { return name; }
  
    // Setter
    public void setName(String newName)
    {
        this.name = newName;
    }
}
  
class Main {
    public static void main(String[] args)
    {
        Person person = new Person();
        // Set the value of the name variable to "kapil"
        person.setName("kapil");
        System.out.println(person.getName());
    }
}


Output

kapil
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments