Skip Top Navigation Bar

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.

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.

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

Use an IDE

If you are using an IDE, create two .java files:

Copy code into the associated .java file.

Your Turn

Grab a Piece of Paper, Let's Try It!
  • In the prior tutorial, you were asked to find an object to model and create a diagram of the class. This could be an object from a game or something physical in your environment. If you can't think of something, consider a spinner or playing card.
  • Implement this class.
  • Create test class to test your class. Create an object of the class and call the methods on this object.