Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Getter and Setter in Java?
3.
Example of Getter and Setter in Java
3.1.
Explanation
4.
Need of Getter and Setter in Java
5.
Naming Convention for Getter and Setter
5.1.
Naming Conventions for Getter Method
5.1.1.
The Syntax for Getter Method
5.2.
Naming Conventions for Setter Method
5.2.1.
The Syntax for Setter Method
6.
 
7.
Bad Practices in Getter and Setter Methods
8.
Advantages of Getter and Setter in Java
9.
Disadvantages of Getter and Setter in Java
10.
Frequently Asked Questions
10.1.
What is getter and setter in java? 
10.2.
What are default getters and setters java?
10.3.
What is final getter and setter in java?
10.4.
How to use Lombok for getter and setter?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Getter and Setter in Java

Author Aditya Gupta
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas! Have you ever played with a toy you could manipulate by pushing or pulling tiny buttons or levers to get it to do various actions? In Java, the getter and setter methods are encapsulated and they are like the tiny buttons used to do various actions in Java. One of the four concepts of object-oriented programming is encapsulation. "Encapsulation" refers to the grouping of data and the functions that use it within an object in object-oriented programming.

getter and setter in java

Getter and setter in Java are techniques that give us a regulated way to access or modify the values of variables. In contrast to a setter method, a getter method "gets" the value of a variable and returns it.

What are Getter and Setter in Java?

Getters and setters are Java methods for gaining access to and changing the contents of private variables, commonly referred to as fields, in a class. The value of a private field is retrieved using a getter method. On the other hand, a private field's value can be changed using a setter method. 

Access to a class's private fields can be restricted using getters and setters. The values of the fields can be accessed and changed in a controlled manner by using getters and setters, which are provided along with making the fields private.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of Getter and Setter in Java

Let’s see an example where we are using Getter and Setter to get the area of a Rectangle.

public class Rectangle {
    private int width;
    private int height;

    // Getter for width property
    public int getWidth() {
        return width;
    }

    // Setter for width property
    public void setWidth(int newWidth) {
        if (newWidth > 0) {
            width = newWidth;
        }
    }

    // Getter for height property
    public int getHeight() {
        return height;
    }

    // Setter for height property
    public void setHeight(int newHeight) {
        if (newHeight > 0) {
            height = newHeight;
        }
    }

    // Method to calculate area of rectangle
    public int calculateArea() {
        return width * height;
    }

    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        r1.setWidth(5);
        r1.setHeight(10);
        int area1 = r1.calculateArea();
        System.out.println("Area of rectangle 1: " + area1);
        Rectangle r2 = new Rectangle();
        r2.setWidth(-5);
        r2.setHeight(20);
        int area2 = r2.calculateArea();
        System.out.println("Area of rectangle 2: " + area2);   
  }
}


Output

output

Explanation

In this code, the Rectangle class 'width' and 'height' fields are accessed and changed using getter and setter, respectively. The getWidth() and getHeight() functions are used to obtain the values for the fields 'width' and 'height'. The setWidth() method sets the field 'width' and the setHeight() method is also used to set the 'height' value.

Need of Getter and Setter in Java

Getter and Setter are used in Java to access and modify values of private fields. Here are some of the reasons why getter and setter are needed.

  • Getter and Setter encapsulate the fields of a class So that the internal state of a class is hidden from the outside world.
     
  • Getter and Setter control access to field class, For example, getter can be used to provide read-only access to a field.
     
  • Setter can be used to verify the values that are set for the field.
     
  • Getter and setter have great compatibility with Java frameworks.

Naming Convention for Getter and Setter

Naming Conventions are necessary to make the code more readable and maintainable.

Naming Conventions for Getter Method

  • The name of the Getter method should start with get keyword followed by the field name, capitalising only the first letter.
     
  • For Boolean Fields name of the getter method starts with is keyword.
     

The Syntax for Getter Method

public class <class_name>{
   Private <data_type> <variable_name>;
   public int get<variable_name>() {
      return <variable_name>;
   }
}


Naming Conventions for Setter Method

  • Name of Setter method should start with set keyword followed by the field name, capitalising only the first letter.
     
  • The setter method should have one parameter of the same type as the field.
     

The Syntax for Setter Method

public class <class_name>{
   private <data_type><variable_name>;
   public void set<variable_name>(<data_type> var) {
      this.<variable_name> = var;
   }
}

 

Bad Practices in Getter and Setter Methods

While using getter and setter in Java we should be careful with some bad practices that should be avoided.

  • Getter and Setter should not expose the internal implementation of the class.
     
  • We should avoid overusing Getter and Setter because it can make the code harder to read sometimes.
     
  • Getter and setter should not provide unrestricted access to the field.  

Advantages of Getter and Setter in Java

We occasionally use Java methods called Getter and Setter while writing long codes in Java. These Methods benefit us in various ways.

  • They assist us in maintaining the structure of our code by hiding internal implementations of the class.
     
  • Getters and setters can limit who has access to or can modify an object's internal data. 
     
  • We can change the code behaviour with the help of getters and setters without changing all the other components of the program.

Disadvantages of Getter and Setter in Java

Using Getter and Setter in Java has several benefits for us but also some significant drawbacks.

  • The use of getter and setter can complicate our code. To view how our objects are accessed and changed, we must implement additional methods and logic, which are difficult to grasp and confusing.
     
  • Our program can occasionally run more slowly when using getters and setters. This is because these methods require some extra steps that can use more time and resources.
     
  • Using getter and setter might increase the size and complexity of our code. To handle each property, we want to access or edit. We must write more methods and logic, which might result in more complex code.
     
  •  Maintaining organised and secure code might take more work when using getter and setter methods.

Frequently Asked Questions

What is getter and setter in java? 

Getters and setters are methods in Java that are used to access and modify the private members of a class. The getter method is used to get the value of a private member, and the setter method is used to set the value of a private member.

What are default getters and setters java?

When we declare a private member in a class, the default getter and setter are generated. The getter method is named get followed by the name of the private member, and the setter method is named set followed by the name of the private member

What is final getter and setter in java?

final getter is a getter method, and setter is a setter method. Both cannot be overridden by subclasses. This is done by declaring the getter or setter method as final.

How to use Lombok for getter and setter?

To use Lombok for getters and setters, we need to add the Lombok dependency to the project and then use the @Getter and @Setter annotations on private members.

Conclusion

This article discusses the topic of Getter and Setter in Java. We hope this blog has helped you enhance your knowledge of Java timestamp. If you want to learn more, then check out our articles.

and many more on our platform Coding Ninjas Studio.

You can also refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! 

Happy Learning!

Previous article
Constructor in Java
Next article
Constructor Overloading In Java
Live masterclass