Skip Top Navigation Bar

Class Creation

Create Classes

Now that we have explored how to identify the needed data and the behaviors of an object, it's time to create a class to define the variables and methods for the attributes and behaviors.

Class Headers

The head of a class consists of the keyword class and the name of the class. The name of the class should be descriptive and should also be the file name.

You will likely see public infront of class in the class header on the exam. The keyword public allows classes that are not packaged together (in the same folder) to have access to each other. For example, you make a project to play a game that has a Dice class. You want to reuse this Dice class in a new game. You can declare Dice as public and the new program files will be allowed to access it given the file path. At this point, the classes you will be writing are all packaged together in one folder for a project and the use of public is not necessary. You can include it or leave it off.

General Format

class ClassName

Dice Class Example

class Dice

After the class header, you will need to have an open brace { and at the end of the file, you will need a close brace }.

Instance Variables

Each attribute that was identified will need to be defined using a variable. To keep the data of an object safe, we will make the data private. This means the data will not be accessible outside of the class unless there is a method to access the values.

An instance variable is an attribute that is unique for each instance of the class. Each object of the class has its own copy of the variable.

The value for the variable is typically set in the constructor. The variables are only defined at this point.

General Format

private <dataType> variableName;

Dice Class Format

private int diceId;

Constructor

Constructors are used to set the initial state, or value of the instance variables, of an object.

A constructor always has the same name as the class.

A class can have many constructors. The default constructor has no parameters and sets default values to the instance variables. Constructors can also contain parameters that can be used to set the initial value, or state, of the instance variables.

When no consturctor is written, Java provides a default constructor where the instance variables are assigned default values based on their types.

General Format

//default constructor
ClassName() {
    //values are assigned to instance variables
}

//non-default constructor
ClassName(<dataType> param, ...) {
    //values are assigned to instance variables
}

Dice Class Constructor Format

//default constructor
Dice() {
    diceId = diceIdCounter;
    diceIdCounter++;
    numSides = 6;
}

//non-default constructor
Dice(int sides) {
    diceId = diceIdCounter;
    diceIdCounter++;
    numSides = sides;
}

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 we will want external classes to call them. 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

<dataType> methodName() {
    return variable;
}

Dice Class Example

int getDiceId() {
    return diceId;
}

int getNumSides() {
    return numSides;
}

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

void methodName(dataType parameter) {
    instanceVar = parameter;
}

Dice Class Example

void setNumSides(int sides) {
    numSides = sides;
}

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.

class Dice {
    //instance variables
    int numSides;
    
    //Constructors
    //Default Constructor
    Dice() { 
        numSides = 6; 
    }
    //Non-Default Constructor
    Dice(int sides) { 
        numSides = sides;
    }

    //Accessor Method
    int getNumSides() {
        return numSides;
    }

    //Mutator Method
    void setNumSides(int sides){
        numSides = sides;
    }
    
    //Other Methods
    int roll() {
        return (int)(Math.random() * numSides) + 1;
    }

    public String toString() {
        return "A dice with " + numSides + " sides.";
    }
}
void main() {
    Dice sixSides = new Dice();
    int value = sixSides.roll();
    IO.println(value);

    //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
}

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.