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.
Accessor methods are used to read values from class variables (instance/static). An accessor method usually starts with a get
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 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 codeJava 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



