Skip Top Navigation Bar

Creating and Using Records

Classes

Consider a blueprint for a house. A builder can construct that same style house at various different addresses. The houses, aka objects, each have a distinct address, they might have a different color, different roof material, maybe a different number of bedrooms or bathrooms. But they are all built on the same blueprint and in the same style. Classes are similar to blueprints. They tell the computer how to create an specific object or instance of the class.

Classes are comprised of data and behaviors.

Records

In the Learn: Introduction to Records tutorial, you learned how to create a new type by creating a record.

Behaviors Defined Through Methods

A method is a block of code that has been defined to perform a specific task or algorithm. Methods can receive arguments making them available to use in the algorithm. Methods can have a return value to provide a result of the algorithm.

Methods can be:

A method has three main parts:

When a record is declared, several instance methods are defined at the same time. There are:

There is an additional method called hashcode; however, it is beyond the scope of this tutorial.

Accessor methods provide the program with the value of the fields. With records, the names of these methods are the same as the names of the fields. For the Vehicle record, the following accessor methods exist:

Calling void Methods

When there is no value being provided as a result of calling the method, the return type of the method is void. These methods are called as follows:

objectName.methodName(argument1, argument2, ...);

If this is a static method, the class name is used instead of the object name. If there are no parameters in the parameter list, the argument list will be empty.

Here is an example call to a void static method from the IO class:

IO.println ("Duke Loves Java");

Calling Non-void Methods

Non-void methods result in a value. This value can be captured and used.

<dataType> variableName = objectName.methodName(argument1, argument2, ...);

Your Turn

Let's try it in the Java Playground.

toString Method

The String toString() method returns a String representation of the object including the values that are assigned to the fields.

equals Method

The equals method is used to compare two objects. When used to compare two objects of the same type, it returns true if they contain the same values for the fields and false otherwise.

Resources

Next Learn Tutorial