Browse by Domains

Getter and Setter in Java

Introduction

In most of the classes, a rule is there that its property is private property. And as we know the classes represent the object, and we always wanted the properties of our object in a secured format. However, we already know that the private properties or variables can only be accessed within the same class. We can read and write access to an object’s private properties through the special class methods called Getters and Setters. In this rule we provide public get and set methods. With the help of the getter method we can read the value of the variable or let us say we retrieve the value. And by using the Setter method we set or initialize respective class fields. However, these special class methods of public get and set methods are by default associated with our classes. But, we can override these default methods by defining the getter and setter methods specifically. 

What are getters and setters in Java? 

As already discussed Getters and Setters are the two conventional special class methods in Java used for retrieving and updating the private properties or variables of a class. Getters and Setters are vigorously used in the Java programming language. But, programmers often make mistakes in implementing this special class method properly. Read the article below to know everything about Getters and Setters in Java. 

Getter method 

A getter method in Java enables us to retrieve or obtain the data of a variable. It returns the value of private members without changing the class type. This method is also called the Accessor method as it accesses the file of classes representing an object. We should always create getter methods for every private property of a class. We can set the access modifier of a variable’s getter method, depending on the level of excess given to a

variable. If we declare the variables within class as private, we will have to add public getter methods for every member. 

The syntax of a getter method in Java is as follows: 

public return type getPropertyName() 

Setter method 

A setter method in Java enables us to update or set the data of a variable. It modifies the value of private members without changing the class type. This method is also called the Mutator method as it modifies or we can say mutates the number of classes representing an object. Like the getter method we should always create setter methods for every private property of a class. And again if we declare the variables within class as private, we will have to add public setter methods for every member. 

The syntax of Setter Method in Java is as follows: 

public void setPropertyName( dataType property value) 

A simple Getter and Setter code 

Below is an example of a General class consisting of private variables and certain getter and setter methods.

public class General{ private int num;
public int getNum() { return this.num; } public void setNum(int num) { this.numb=num; } }

In the above code General is a class consisting of private variable num. Though num is a private class it can not be accessed outside the class. So we have to evoke the getter, getNum() and the setter, setNum() to access and modify the values of private property num of the General class. 

Why do we use the Getter and Setter Method? 

The Getter and Setter method protect our class properties from unwanted external changes. There can be critical consequences of using different means to access the private members other than the Getter and Setter methods. 

Besides, there is a fundamental principle called Encapsulation in Object Oriented Programming Language. When a property is secured or hidden by a private modifier and can be accessed only by means of the getter and Setter method, the code is said to be Encapsulated. Moreover, the OOPs concept was developed by taking the programmers privacy into consideration. Thus Getter and Setter protects our code from violation of the most fundamental principle of Objects Oriented Programming Language, Encapsulation.

What if we don’t have a Getter and Setter Method in Java? 

Suppose if we don’t have a Getter and setter method in a programming language. So, what if we wanted to change the value of properties of our class. Well we have to make these properties public, protected, or default. Then we have to use a dot (.) Operator outside the class. Let us see some of the consequences of doing this. 

● Since we are using the properties or values outside the class, without the Getters and Setters method we are making them public, protected or default. By doing this we violate the fundamental Object Oriented Programming principle ie Encapsulation. We are losing control over our data. 

● Non-private variables can be accessed and changed by anyone outside the class. Thus we cannot achieve Immutability. 

● Conditional logic can not be applied to the change of properties. Suppose you are running a corporate organization and you made class Workers with a property retirementage:

public class Workers{ public string name; public int retirementage; } Though we have set these properties public to gain access from outside the Workers class. Anyone can access this class and do whatever they want to do with the retirementage member of the class. We cannot validate the change in any way. public class retirementage modifier { private Workers workers = new workers(“Walt”,45); private void modify retirementage() { workers.retirementage=25; } }

Also Read: Abstract Class and Encapsulation in JAVA

Common Mistakes 

1)Using Getter and Setter with less restricted variables 

There is no sense of using Getter and Setter Method for a public variable. It can easily be accessed using a dot (.) Operator. 

public class Workers{ public string name; public int retirementage; } public void setName(string name){ this.name=name; } public string getName() { return this.name; }

2)Assignment of Object Reference Directly in setter 

If we assign the object reference directly in Setter Method, both these references (from inside and the outside code) are returned to a single object in the memory. So we can provide the copy of the object instead of returning the reference directly. By using this we can make the state of the object independent from the existing internal one. The outside code is now obtaining a copy of the internal object. 

public void setWorkers(Workers workers){ 

this.workers=workers; 

Now makin the copy of all elements from internal object

public void setWorkers(Workers workers){ this.workers.setName(workers.getName()); this.workers.setretirementage(workers.getretirementage()); }

3)Returning the object reference directly into getter 

Similarly, if we return the object reference directly into the getter method anyone can change the state from outside using its reference. Therefore, again we can provide the copy of the object instead of returning the reference directly. See the changed new code below: 

private void modifyAge() { Workers workersb=getworkers(); workersb.setretirementage(60); } public workers getworkers(){ retrurn new Workers(this.workers.getName(), this.workers.getretirementage()); }

Now give a short look over advantages of getter and setter in java 

As you know, providing getter and setter methods to access any class field in Java may seem pointless and meaningless at the very first place, simply because you can make the field public. Also it is available in Java programs from anywhere. But actually, many java programmers do this only in the early days. And once you gain some experience

and start thinking in terms of enterprise application or production code, you can easily assume and estimate how much maintenance trouble it can cause. 

According to the SDLC process, we know that software spends more time on maintenance than development. 

And it is worth having ease of maintenance as one of the development goals. Therefore we prefer the approach of getter and setter in java always and it is one of the Java coding best practices. 

There are some advantages of getter and setter over public fields: 

1) With the help of Java, you can easily make the class accessible with many open source libraries and modules such as display tags by making fields private and by including getter and setter and following the javabean naming convention. It always uses a combination of reflection and the Javabean naming convention to load and access fields dynamically. 

2) We can give Subclass an opportunity to override this method with getter and setter and return what makes more sense in the context of the subclass. 

3) This 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. We can easily place breakpoints or a print statement to see which thread is accessing and what values are going out. 

4) We allow inheritors to change the semantics of how the property behaves and is exposed by overriding this method.

class Person { // private = restricted access private String name; // Getter public String getName() { return name; } // Setter public void setName(String newName)
<!-- wp:paragraph -->
<p>{&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>this.name = newName;&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>class Main {&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>public static void main(String[] args)&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Person person = new Person();&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>// Set the value of the name variable to "Manish"&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>person.setName("Manish");&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>System.out.println(person.getName());&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}&nbsp;</p>
<!-- /wp:paragraph -->

The output of this code is: 

Manish

I hope you might have got the basic idea about getter and setter in java. And now you can easily proceed further to explore more in the field of Java.

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility
Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top