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!”