Writing Java Methods: Msury - Mahunnah@ifm - Ac.tz
Writing Java Methods: Msury - Mahunnah@ifm - Ac.tz
Dr. Mahunnah, M
[email protected]
https://mahunnah.wordpress.com/
Method Declarations
Let’s now examine method declarations in more detail
A method declaration specifies the code that will be executed when
the method is invoked (called)
When a method is invoked, the flow of control jumps to the method
and executes its code
When complete, the flow returns to the place where the method
was called and continues
The invocation may or may not return a value, depending on how
the method is defined
Method Control Flow
If the called method is in the same class, only the method name is
needed
Method Control Flow
The called method is often part of another class or object
Accessors and Mutators
Because instance data is private, a class usually provides services
to access and modify data values
An accessor method returns the current value of a variable
A mutator method changes the value of a variable
The names of accessor and mutator methods take the form getX
and setX, respectively, where X is the name of the value
They are sometimes called “getters” and “setters”
Mutator Restrictions
The use of mutators gives the class designer the ability to restrict a
client’s options to modify an object’s state
A mutator is often designed so that the values of variables can be
set only within particular limits
For example, the setFaceValue mutator of the Die class should
have restricted the value to the valid range (1 to MAX)
Die.java
Die.java
RollingDice.java
RollingDice.java
RollingDice.java Output
The Die Class
Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}
Printing Objects
By default, Java doesn't know how to print objects:
// desired behavior
System.out.println("p is " + p); // p is (10, 7)
The toString method
The toString() method tells Java how to convert an object into a
String
Point p1 = new Point(7, 2);
System.out.println("p1: " + p1);
//the above code is really calling the following:
System.out.println("p1: " + p1.toString());
Point@9e8c34
Driver Program
A driver program drives the use of other, more interesting parts of a
program
Driver programs are often used to test other parts of the software