×

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier is typically used to embellish class fields. As a result, the getter and setter methods require public access specifiers to allow access to them.

The need for the getter-setter method:

One could argue that the getter and setter methods should be removed and the class fields should be made public. However, this kind of coding is bad, because one might give the class fields an absurdly high value. Let's use an illustration to assist you comprehend it.

public class GetterSetterExample  
{  
    public salary;  
      
    public storeSalDB(int sal)  
    {  
    }  
      public static void main(String argvs[])   
    {  
      GetterSetterExample obj = new GetterSetterExample();      
       obj.sal = -50000;  
      obj.storeSalDB(sal);  
  
    }  
}  

Observe how the code is incorrectly recording a negative salary in the database. A negative salary is never credited to an employee's account by the company. Because the wage variable was declared with such a public access specifier, a ridiculous amount was assigned to it. The code shown above should be written as follows:

public class GetterSetterExample   
{  
    private sal;  
     void setSal(int a)  
    {  
        if(a< 0 )  
        {  
            a = -a;  
        }  
        this.sal = a;  
    } 
    int getSal()  
    {  
        return this.sal;  
    }  
     public storeSalDB(int sal)  
    {  
         System.out.println("Hi ")  
    }  
     public static void main(String argvs[])   
    { 
        GetterSetterExample obj = new GetterSetterExample();      
        obj.setSal(-50000);  
        int sal= obj.getSal();  
      obj.storeSalDB(sal);  
  }  
}  

We now have more control over the information we submit to a database to store. Every time the salary becomes negative, we turn it into a positive before passing it into the database to be stored. Therefore, irrespective of the value we pass to the setter technique, the setter method's if-block handles the ludicrous value, giving us better control over the salary value.

Getter Setter Java Program:

FileName: GetterSetterExample.java

class Employee   
{  
    private int empId;  
    private String empName;  
    private String empDesignation;  
    private String empCompany;  
 public int getEmpId()   
    {  
        return empId;  
    }  
    public void setEmpId(final int empId)   
    {  
        this.empId = empId;  
    }  
    public String getEmpName()   
    {  
        return empName;  
    }  
    public void setEmpName(final String empName)   
    { 
        if(empName == null ||  empName.length() <= 0)   
        {  
            throw new IllegalArgumentException();  
        }  
        this.empName = empName;  
    }  
    public String getEmpDesignation()   
    {  
        return empDesignation;  
    }  
    public void setEmpDesignation(final String empDesignation)   
    {  
        this.empDesignation = empDesignation;  
    }  
    public String getEmpCompany()   
    {  
        return empCompany;  
    }  
      
    public void setEmpCompany(final String empCompany)   
    {  
        this.empCompany = empCompany;  
    }  
    @Override  
    public String toString()   
    {  
        String str = "Employee: [id = " + getEmpId() + ", name = " + getEmpName() + ", designation = " + getEmpDesignation() + ", company = " + getEmpCompany() + "]";  
        return str;  
    }  
}  
public class GetterSetterExample1   
{  
    public static void main(String argvs[])   
    {  
        
        final Employee emp = new Employee(); 
        emp.setEmpId(108);  
        emp.setEmpName("Kathrik");  
        emp.setEmpDesignation("Software Developer");  
        emp.setEmpCompany("ABC Corporation"); 
        System.out.println(emp.toString());  
    }  
}  

Output:

Employee: [Id=108, Name=Karthik, Designation=Software Developer, Company=ABC Corporation]

Negative Getter and Setter Methods Practices:

When using the getter and setter methods, users frequently engage in a number of undesirable habits.

Bad Practice 1:

Use of getter and setter for a variable with a low restricted scope is a bad practise.

public salary;  
  
    void setSal(int a)  
    {     
        sal = a;  
    }  
          
    int getSal()  
    {  
        return sal;  
    }  

It is clear that one may immediately access the variable salary from the main method, which is problematic and renders the getter and setter methods unnecessary.

Bad Practice 2:

Using an object - oriented approach in the setter method is a bad practise . Consider the program below.

FileName: GetterSetterExample1.java

class PQR  
{  
private int[] v;  
  
void setV(int[] a)   
{  
this.v = a;   
}  
  
void display()  
{  
int size = (this.v).length;  
  
for(int i = 0; i < size; i++)  
{  
System.out.print(this.v[i] + " ");  
}  
}  
} 
public class GetterSetterExample2  
{  
public static void main(String argvs[])  
{  
PQR obj = new PQR();  
  
int mainArr[] = {3, 5, 6, 7, 8, 9};  
  obj.setV(mainA);  
  obj.display();  
  mainA[0] = -1;  
System.out.println();  
  obj.display();  
}  
}

Output: 

3 5 6 7 8 9
-1 5 6 7 8 9

Explanation:

Reference management can be a little challenging. The value for array mainA[] in the aforementioned code was modified at index 0 . It also appeared in the array val[], though. Since the v[] array has been marked private, it shouldn't take place, and any code from classes other than PQR are also not expected to alter it. The references, though, have caused things to be confusing.

This defeats the objective of the setter function because anything we update inside the mainA[] also affects the v[] array. Additionally, adding the secret access specifier towards the v[] array serves no use because the output clearly shows that the content of the v[] array may be changed in the main method.

The code shown above might be written as follows:

class PQR   
{  
private int[] v;  
  
void setV(int[] a)   
{  
int size = a.length;  
v = new int[size]; 
for(int i = 0; i < size; i++)  
{  
this.v[i] = a[i];  
}  
}  
 void display()  
{  
int size = (this.v).length;  
for(int i = 0; i < size; i++)  
{  
System.out.print(this.v[i] + " ");  
}  
}  
}  
public class GetterSetterExamplE
{  
public static void main(String argvs[])  
{  
PQR obj = new PQR();  
  
int mainA[] = {3, 4, 6, 8, 7, 9};  
 obj.setV(mainA); 
obj.display();  
mainA[0] = -1;   
System.out.println();  
obj.display();  
  
}  
}

Output:

3 4 6 8 7 9
3 4 6 8 7 9

Explanation:

The array arr elements ['s are being deep copied in the code above. We are making a whole new array in line 11. This means that the v[] does not refer to the a[]. Additionally, only the element's data are copied in line 17. As a result, the v[ ] does not update when we alter the value of a 0th member at line 53. As a result, the code above respects the private member variable v ['s] encapsulation.

Bad practice 3:

A getter method that returns an object reference. Take note of the program below:

class PQR   
{  
private int[] v= {62, 3, 8, 11, 7, 1};  
public int[] getV()  
{ 
    return v;  
}  
void display()  
{  
int size = (this.v).length;  
 for(int i = 0; i < size; i++)  
{  
System.out.print(this.v[i] + " ");  
}  
}  
}  
public class GetterSetterExample
{  
public static void main(String argvs[])  
{  
PQR obj = new PQR();  
int a[] = obj.getV();  
obj.display();  
a[0] = -1;   
System.out.println();  
obj.display();  
}  
}  

Output:

62 3 8 11 7 1
-1 3 8 11 7 1

Explanation:

The references are not being handled correctly in the code above. The reference to the array is returned by the getter method. The array v[], which is designated private inside the class PQR, is referenced by the a[], which stores its reference. The encapsulation of a class PQR is broken since a[] can alter the v[] because the connection to the outside world was made public.

The right response to the aforementioned is:

class PQR  
{  
private int[] v = {7, 3, 6, 12, 71, 2};  
 public int[] getV()  
{  
int size = v.length;  
int temp[] = new int[size];  
for(int i = 0; i < size; i++)  
{  
temp[i] = v[i];  
}  
return temp;  
}  
void display()  
{  
int size = (this.v).length;  
for(int i = 0; i < size; i++)  
{  
System.out.print(this.v[i] + " ");  
}  
}  
}  
public class GetterSetterExample  
{  
public static void main(String argvs[])  
{  
PQR obj = new PQR();  
 int arr[] = obj.getV();  
obj.display();  
a[0] = -1;  
System.out.println();  
obj.display();  
}  
}  

Output:

7 3 6 12 71 2
7 3 6 12 71 2

Explaination:

In the code above, the private array's reference is not broadcast to the external world. A new array is generated in the getter method and its reference is given to the main procedure. As a result, line 54's change to the data at the 0th index affects the temp[] array rather than the private array val[]. As a result, the class PQR's encapsulation is preserved because the reference towards the array val[] is just not made public.

class PQR
{  
private String str= null;  
void setV(String s)   
{  
this.str = s;  
} 
void display()  
{  
System.out.println( "The String is: " + this.str);  
}  
}  
public class GetterSetterExample
{ 
public static void main(String argvs[])  
{ 
PQR obj = new PQR();  
String inputStr = "Hello Miss!";  
obj.setVal(inputStr);  
obj.display();  
inputStr = "Hello Miss!";  
 obj.display();  
}  
}

Output: 

The String is: “Hello Miss!”
The String is: “Hello Miss!”

Related Topics

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.