Writing Methods
Let's write methods to represent the behaviors of the class.
Methods
The behaviors that have been identified are implemented by writing methods for the class.
Some methods are internal to the class and external classes should not be able to call them. In these cases, the methods might be private.
Some methods will need to be called by external classes. In these cases, the methods might be public. The use of public is not necessary if the classes are in the same package.
Methods have a return type.
- If the method is performing an action, but not producing a value, the return type is
void. - If the method is producing a value, the return type will be the type of this value.
- Methods only have one return type. So if you want to return more than one value, you could create a new type in the form of a record.
Accessor Methods
This type of method allows the object to obtain a copy of the value of class or instance variables. These methods will have a return type that is the type of the variable it is returning.
General Format
Dice Class Example
Mutator Methods
This type of method allows the object to modify the public instance variables. These methods will have a return type of void and will take a parameter tha is the new value.
General Format
Dice Class Example
Foldi
Use these images to create a helpful guide for creating a class.
- Print these two images back to back.
- Fold in half along the vertical line.
- Cut along the horizontal lines between the terms and definitions of the terms.
Outside of the Foldi
Inside of the Foldi
Dice Class Code
Either use the Java Playground or an IDE to demonstrate this code to simulate rolling a die.
Use the Java Playground
- Predict the output from running the body of main for testing.
- Run the code to determine if your prediction was correct.
- To the main:
- add statements to call the accessor method and print the number of sides.
- add a statement to change the number of sides to 10.
- add statements to roll the dice and print the value.
- add a statement to use the toString method.
- Run the code to test the additions you have mad to main
Use an IDE
If you are using an IDE, create two .java files:
- Dice.java
- DiceTester.java
Copy code into the associated .java file.
Your Turn
|
Grab a Piece of Paper, Let's Try It! |
|