Accessor methods are used for initializing and accessing the value of instance variables. The value of these instance variables can be used further in the program. For creating accessor methods, it is required to create two methods among which one method is used to initialize the value and other is used to retrieve the value. An accessor method makes the program more readable and understandable. Moreover, accessor methods are similar to any other method, as can be seen from Program.
Implementing accessor methods.
// A program to find area of a square.
import java.io.*;
class AccessorMethodClass
{
int side;
//This method is used for initializing the value of global variable ‘side’
public void setSideValue(int a)
{
side = a;
}
// This method is used for getting the value of the global value
public int getSideValue()
{
return side:
}
public static void main(String args[ ])
{
int area, side;
accessorMethodClass ob=new accessorMethodClass();
ob.setSideValue(10); // Initializing the value of global variable
side = ob.getSideValue(}; // Retrieving the value of Global variable
area = side * side; // Finding the area of square.
System.out.println(“The area of Square is” +area);
}
}
The output of Program is as shown below:
The area of Square is 100
In Program the global variable side is initialized by the method setSideValue(int a) and its value is retrieved by the method getSideValue(). Here, the words like set and get make the functionality of accessor methods more clear even though it is not a part of any rules or specifications.
Accessor methods can also have names similar to their instance variable and Java performs the appropriate operation based on the use of these methods and variables, as shown in Program.
Using accessor methods II.
// A program to find the area of a square which is equal to square of the side.
import java.io.*;
class AccessorMethodClass
{
int side;
// Note that method name and variable name is same
public void side(int a)
{
side = a;
}
public int getSideValue()
{
return side;
}
public static void main(String args[])
{
int area, sidevalue;
AccessorMethodClass ob = new AccessorMethodClass();
ob.side(10);
sidevalue = ob.getSideValue{);
area = sidevalue*sidevalue;
System.out.println(“The area of Square is”+area);
}
}
The output of Program is as shown below:
The area of Square is 100
There are some problems with the convention used for having same name as described in the above program.
• Using same name for the instance variable and method may make the program less readable and understandable. Providing meaningful names to the variables and methods with respect to their functionality is a good programming practice.
• Adopting this type of convention violates the essentials of structured programming.