Tuesday, July 7, 2009

Java Accessor method

Accessor methods

In order to implement encapsulation, that is, we don't want any objects to just access our data anytime, we declare the fields or attributes of our classes as private. However, there are times wherein we want other objects to access private data. In order to do this, we create accessor methods.

Accessor methods are used to read values from class variables (instance/static). An accessor method usually starts with a get. It also returns a value.

For our example, we want an accessor method that can read the name, address, english grade, math grade and science grade of the student.

Now let's take a look at one implementation of an accessor method,

public class StudentRecord
{
private String name;
:
:
public String getName(){
return name;
}
}
where,

Public - means that the method can be called from objects outside the class
String - is the return type of the method. This means that the method should return a value of type String
GetName - the name of the method
() - this means that our method does not have any parameters

The statement,

return name;

in our program signifies that it will return the value of the instance variable name to the calling method. Take note that the return type of the method should have the same data type as the data in the return statement. You usually encounter the following error if the two does not have the same data type,

StudentRecord.java:14: incompatible types
found : int
required: java.lang.String
return age;
^
1 error

Another example of an accessor method is the getAverage method,

public class StudentRecord
{
private String name;
:
:
public double getAverage(){

double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;

return result;
}
}

The getAverage method computes the average of the 3 grades and returns the result.

Related Post:

Java Tutorial switch statement source code

Java tutorial source code get input from keyboard

Java Tutorial Using JOptionPane to get input

Java tutorial Decision Control Structures: if statement

PHP Tutorial

Java programing source code sample printing characters

Java tutorial if-else statement

C programming sample source code: Sum of 2 numbers

Java Programming Features