Accessor methods Mutator Methods

J.E.D.I

10.4.1 Accessor methods

In order to implement encapsulation, that is, we dont 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 instancestatic. An accessor method usually starts with a getNameOfInstanceVariable. 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 lets 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 Introduction to Programming I 153 J.E.D.I 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.

10.4.2 Mutator Methods

Now, what if we want other objects to alter our data? What we do is we provide methods that can write or change values of our class variables instancestatic. We call these methods, mutator methods. A mutator method is usuallyu written as setNameOfInstanceVariable. Now lets take a look at one implementation of a mutator method, public class StudentRecord { private String name; : : public void setName String temp { name = temp; } } where, public - means that the method can be called from objects outside the class void - imeans that the method does not return any value setName - the name of the method String temp - parameter that will be used inside our method The statement, name = temp; assigns the value of temp to name and thus changes the data inside the instance variable name. Take note that mutator methods dont return values. However, it contains some program argument or arguments that will be used inside the method. Introduction to Programming I 154 J.E.D.I

10.4.3 Multiple Return statements