Getters and Setters in Java

Getters and Setters are two conventional methods which are used for retrieving and updating the value of a variable. By the use of Getters and Setters, the programmer can control how his important variables are accessed and updated in a correct manner, such as changing the value of a variable within a specified range.

Providing getters and setters method for accessing any field of class in Java may look unnecessary because you can make the field public and it’s accessible from everywhere in Java program.

In fact, many programmers do this in there early days but once you start thinking in terms of the enterprise application or production code, you will start seeing how much trouble it can create in terms of maintenance.

Getter and setter method gives you centralized control on how a particular field is initialized and provided to the client which makes validation and debugging much easier.

You can simply put a breakpoint or print statement to see which thread is accessing and what values are going out.

Rules for get/set:

  • The getter method’s prefix must be get, if the property is not of boolean type
  • The getter method’s prefix can be get or is if the property is of boolean type
  • The setter method’s prefix must be set
  • The signature of the setter method must be public with void as return type, and an argument that represents the property type
  • The signature of the getter method must be public with no argument, and a return type matching the setter method of that property





public V/S get/set:

  • with get/set we have options to read or write or both. But, public data always have both the options
  • It is possible to validate the data with the set. But, public data cannot be validated

Constructors :

They are special member functions and are used for initialization of user-defined data types in multiple forms.

  • Constructors must have the same name as of a class
  • They do not have any return type, not even void
  • Constructors are Executed automatically whenever an object is created (new)
  • Constructors are executed only once for an object

 Constructor Rules :

  • Firstly, If we do not write a constructor, Java adds a default constructor that initializes all numeric member data is default initialized by 0(Zero), Boolean by false, character by space and reference type by null
  • Secondly, Number of constructors in class equals to the Number of ways objects can be created

Getter and Setter
For Complete programs of Getter & Setter and its Implementations visit codedbug GitHub Repo

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?