Types of classes, part 2

Today I will continue my series on classes in Java. To review where we are, you can read this post.

First of all, we need to add a couple of methods to our class. There are two other types of methods in classes: reporters and mutators. A reporter does exactly that. As you might notice, our instance variables are private, meaning that only that class can see it. So if we want to know certain information about the student, we must write a method that looks at the variable in question and reports it. A mutator method changes the object in some way. So, that being said, lets write a couple of these methods.

………..

public String tellName(){
return name;
}

public void computeGPA(float newAvg){
float oldAvg= gpa;
gpa= (oldAvg+newAvg)/2;
}

Here, we have added two methods to our class- a reporter and a mutator. Our reporter, tellName, looks at the current value of String name and returns it. Since we are returning a value, the method must be of the type we are returning. It is public so it can be accessed from outside our class. Now, here I just wrote one for name, but to get the other values (age, gpa, status), you must write a reporter method for each variable, as it’s respective type (an age reporter would be of type int).

Our next method is a mutator that figures out a new gpa. This is a simple one that accepts a new GPA from the client and averages the new and old one together. This method is not returning anything, just doing a calculation, so it is a void method. It is accepting a variable of type float, which we declare in the parentheses before the do work in the method. Then we perform the calculation. We declare a new variable called oldAvg that gets the value of gpa, and then we assign the new value to gpa.

That is all there is to other types of methods. They can be as simple or as complicated as you see fit. Next time, I will talk about inheritance and extensions. Later!

Leave a Reply

Your email address will not be published. Required fields are marked *