Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Getter and Setter in Java

Last Updated on October 16, 2023 by Ankit Kochar

Getter and Setter in java are part of the encapsulation. Encapsulation, a fundamental principle within the realm of object-oriented programming, stands as one of its four core pillars. In Java, encapsulation signifies the practice of bundling data together with the methods responsible for manipulating that data within an object. Its primary purpose is to shield the inner workings of an object’s implementation from external users, offering them access only to essential information. Encapsulation serves as a safeguard for data integrity, thwarting any unauthorized access to data attributes and methods. Moreover, it upholds an object’s state integrity, permitting alterations to be carried out exclusively through designated methods. This makes it easier to change the implementation without affecting the code that uses the thing. We use getter and setter in java to access the data that is hidden by encapsulation.

What are Getter and Setter in Java?

Getter and Setter in Java are methods used to access and set the values of an object’s attributes, respectively. They are also referred to as accessor methods and mutator methods.

Within the domain of Object-Oriented Programming (OOP), encapsulation emerges as a cornerstone concept. It entails the act of concealing the internal intricacies of an object while solely revealing its public interface. This practice serves as a catalyst for advancing the principle of information hiding, a pivotal facet of OOP. Getter and setter in java are an example of how this can be achieved in Java.

A getter method, also known as an accessor method, is used to retrieve the value of an object’s attribute.

A setter method, also known as a mutator method, is used to set the value of an object’s attribute.

It is important to note that getter and setter methods should be declared as public. This allows other classes to access the attributes of an object through these methods. In addition, setter methods are often used to enforce certain constraints or validation checks on the values being set for an attribute. For example, a setter method might be used to ensure that a person’s age is set to a valid value between 0 and 120.

Getter and setter in java are also useful when you want to change the implementation of an attribute’s access at a later time. For example, you might start by storing an attribute as a simple variable, but later decide to store it in a database. By using getter and setter in java, you can make this change without affecting the rest of the code that uses the attribute.

In conclusion, getter and setter in java are key aspects of OOP and Java programming. They allow you to control access to an object’s attributes, enforce constraints and validations, and promote information hiding. Whether you are working on a simple class or a complex application, getter and setter in java are useful tools for creating well-designed, maintainable code.

Examples of Getter and Setter in Java

Here we will look at the example where we are using getter and setter in java for accessing private members.

Example 1: Getter and setter methods in employee class.
Here we are looking at the example that has a class named employee with some private members.

class Employee{
    private String name;//private variable
    private int id;//private variable

    public void setName(String n) {
        this.name=n;
    }
    public String getName() {
        return name;
    }
    public void setid(int r) {
        this.id=r;
    }
    public int getid() {
        return id;
    }
}

public class Main {

    public static void main(String[] args) {
        Employee s1= new Employee(); 
        s1.setName("PrepBytes");
        s1.setid(19);
        System.out.println(s1.getName());
        System.out.println(s1.getid());

    }
}

Output

PrepBytes
19

Explanation of the above code
Two private variables, "name" and "id," are present in the "Employee" class in the program above. We are unable to directly access those variables outside of the class, which is an example of data hiding or encapsulation. In order to obtain the data, we use getters such as the getName() and getid() methods, and in order to update or alter the values, we use setters such as the setName() and setid() methods. To access the data members of the current object it is pointing to, we utilized "this pointer" within setters. Here, we can easily change the values of the variables without having direct access to them by simply using the setter procedures, and we can print the values by calling the getter routines. So we have used getter and setter in java in the above example to set the value of private members and access them.

Example 2: Getter and Setter methods for maintaining the value within the range
In this example, we have a class named SetGet where we are looking at whether the number is in a given range or not.

import java.io.*;

class SetGet {

    private int num;

    public void setNumber(int number)
    {

        if (number < 15 || number > 100) {

            throw new IllegalArgumentException();
        }
        num = number;
    }

    public int getNumber() { return num; }
}
class Prepbytes {

    public static void main(String[] args)
    {
        SetGet obj = new SetGet();

        obj.setNumber(20);

        System.out.println(obj.getNumber());
    }
}

Output

20

Explanation of the above code
In the above code, we have a class named SetGet where we are seeing whether the value is in the range of 15 and 100 or not we are using getter and setter to see the number and if not in the range then set the value. It is used for changing the value rather than changing the value directly.

The Need for Getter and Setter in Java

Getter and setter in Java are essential when implementing encapsulation, a key principle of object-oriented programming. Encapsulation refers to the practice of hiding the internal state and behavior of an object and exposing only what’s necessary to the outside world. This allows you to control access to an object’s data and behavior, making it easier to maintain and modify the code over time.

Getter and setter in java are used to provide access to an object’s private data. The getter method retrieves the value of a private instance variable, while the setter method sets the value of that variable. By using getter and setter in java, you can control how other parts of your code interact with an object’s data. For example, you can enforce constraints on the values that can be set, validate data before it’s set, and trigger actions when data is updated.

One of the main benefits of using getter and setter in java is that they allow you to change the implementation of an object’s internal state without affecting other parts of the code that use the object. For example, if you store an object’s data in a database, you can switch to using a different database without having to change the code that uses the object, as long as the getter and setter methods continue to work the same way.

Getter and setter methods also help to improve the maintainability and readability of your code. By providing a consistent and well-documented way for other parts of your code to interact with an object, you make it easier for others (including yourself) to understand and modify the code.

Another advantage of getter and setter methods is that they enable you to control access to an object’s data. You can use the private access modifier to make instance variables private, which means that they can only be accessed within the object. By providing getter and setter methods, you can control how other parts of your code interact with the object’s data, and you can change the implementation of the getter and setter methods as needed to enforce security, validate data, or perform other tasks.

Summarising getter and setter methods are an important aspect of Java programming and a key tool for implementing encapsulation. They allow you to control access to an object’s data, maintain and modify the code over time, and improve the readability and maintainability of your code. By using getter and setter methods, you can write more robust and flexible code that is easier to maintain and understand.

Naming Convention for Getter and Setter in Java

We have to follow the naming convention while using getter and setter in java.
Getter method (used to retrieve the value of an instance variable): Starts with the word "get". Followed by the name of the instance variable, with the first letter capitalized (e.g. for a variable "name", the getter method would be "getName").

Setter method (used to set the value of an instance variable): Starts with the word "set". Followed by the name of the instance variable, with the first letter capitalized (e.g. for a variable "name", the setter method would be "setName").

Syntax for Getter Method

The syntax for using the getter method in java is given below:

public class Person {
   private int age;

   public int getAge() {
      return age;
   }
}

Syntax for Setter Method

The syntax for using setter method is given below:

public class Person {
   private int age;

   public void setAge(int age) {
      this.age = age;
   }
}

Bad Practices in Getter and Setter in Java

Using getter and setter in java is a common practice., but there are some common pitfalls to avoid to make your code more maintainable and easier to understand. Here are some of the bad practices to avoid when using getters and setters in Java:

  • Exposing private instance variables directly: Getter and setter methods are used to provide a controlled way to access and modify the instance variables. Avoid using the getter and setter methods as a way to directly access private instance variables. This can lead to unexpected changes in the state of an object, making the code harder to maintain.
  • Not following naming conventions: Getter methods should start with the word "get" followed by the name of the instance variable with the first letter capitalized, while setter methods should start with the word "set". Not following these naming conventions can lead to confusion and make the code harder to understand.
  • Not providing appropriate access control: Make sure to set the access level of the getter and setter methods appropriately. The getter method for a private instance variable should be public, while the setter method could be protected or private to restrict write access to the instance variable.
  • Exposing mutable objects: If a getter method returns a reference to an internal mutable object, it can be changed from outside the class. This can lead to unexpected changes in the internal state of the class. To prevent this, return a defensive copy of the object from the getter method.
  • Not using meaningful parameter names: The parameter names used in setter methods should be descriptive and meaningful, rather than just "value". This makes the code easier to understand and reduces the possibility of bugs.
  • Not using proper method signatures: Getter methods should have no parameters, while setter methods should have one parameter that corresponds to the instance variable being set. Having more than one parameter or not having any parameters can lead to confusion and unexpected behavior.

By avoiding these bad practices, you can make your code more maintainable, reliable, and easier to understand. Adhering to best practices and following conventions can make your code more readable, reusable, and maintainable in the long run.

Advantages of using Getter and Setter in Java:

The advantages of using getter and setter in java are gien below:

  • Encapsulation: Getter and setter methods provide a way to access and modify instance variables in a controlled manner, helping to encapsulate the internal state of an object. This can improve the overall security and reliability of the code.
  • Flexibility: Getter and setter methods provide a way to change the internal representation of an object without affecting the external code that uses the object. This can make the code more flexible and easier to maintain.
  • Easy Access: Getter methods provide an easy way to access the values of instance variables from outside the class, without having to directly access the instance variables.

Disadvantages of using Getter and Setter in Java:

The disadvantages of using getter and setter in java are explained below:

  • Overhead: Getter and setter methods add an extra layer of abstraction to the code, which can result in performance overhead.
  • Complexity: Having too many getters and setters can make the code more complex and harder to understand, especially if they are not properly documented.
  • Violating Encapsulation: Getter and setter methods can be used to directly access private instance variables, which can lead to unexpected changes in the state of an object and violate the principles of encapsulation.

Overall, getter and setter methods can be useful for maintaining the internal state of an object and providing controlled access to instance variables. However, it is important to use them judiciously and avoid the potential disadvantages.

Conclusion
In Java, getters and setters play a crucial role in maintaining the principle of encapsulation and ensuring data integrity within object-oriented programs. Getters allow controlled access to the private attributes of a class, while setters enable controlled modification of those attributes. By following best practices and conventions for naming and using getters and setters, Java developers can create robust and maintainable code that adheres to the principles of encapsulation.

FAQs Related to Getter and Setter in Java

Here are some of the FAQs related to to Getter and Setter in Java:

1. What naming conventions should I follow when naming getter and setter methods in Java?

Answer: Getter methods should begin with "get" followed by the variable name (e.g., "getName" for a variable "name"). Setter methods should start with "set" followed by the variable name (e.g., "setName" for a variable "name").

2. Can I have a getter without a setter or vice versa in a Java class?

Answer: Yes, it is possible to have only a getter or only a setter in a Java class. Depending on the use case, you may not need both getter and setter methods for every attribute.

3. What is the purpose of making instance variables private and providing getters and setters?

Answer: Making instance variables private and providing getters and setters enforces encapsulation, ensuring that data can only be accessed and modified in controlled ways, which helps maintain data integrity.

4. Can I have a getter and setter with different access modifiers (e.g., one private and one public)?

Answer: Yes, it is possible to have different access modifiers for getters and setters. For example, you might have a private variable with a public getter to allow read-only access but restrict write access.

5. Are getter and setter methods always necessary for every private variable in a class?

Answer: No, getter and setter methods are not always necessary for every private variable. You should provide them when you want to control access to the data or when you need to enforce business rules on data modifications.

Leave a Reply

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