Concepts / Java Classes and Instance Variables

Java Classes and Instance Variables

A Java record is an object that belongs to a special kind of class called a record class.

  • Programming

Predicting What a Short Definition Declares

Below is a short Java definition. It names a new kind of object and lists the pieces of data each object of that kind will hold. Before reading any explanation, look at the line and ask yourself two things: what is the name of the new kind of object, and what pieces of data does every such object carry? Write down your guess. The rest of this article works out what that single line means and how it is used.

What a Record Class Is

Definition

A Java record is an object that belongs to a special kind of class called a record class.

The phrase special kind of class matters. A record is not just any object: its class is a record class. Nothing more than the essential data description is needed for the simplest version of a record class to work. In that simplest case, the record class specifies only the set of instance variables that represent the fields of the record. Because nothing else is required, the whole definition can be very short.

Instance variables are the named pieces of data that each object of the class holds. In a record, these instance variables are the fields of the record. Each object gets its own values for them, while the class definition itself only states which names exist and what type each one has.

Reading the Record Definition Line by Line

The source example declares a record class named FullName. Its two instance variables are both of type String and are named firstName and lastName. The class name comes first, and the variables appear in parentheses directly after it. The definition ends with a pair of braces that enclose an empty class body. The complete definition reads as follows.

java
Notes on the code
  • public: access keyword placed before the word record
  • record: marks this as a record class
  • FullName: the class name
  • (String firstName, String lastName): the instance variables, which are the fields of the record
  • {}: the empty class body, which adds no members beyond the parentheses
publicaccess keyword before therecord keywordrecordmarks a record classFullNamethe class name, first afterthe keywords(String firstName,String lastName)instance variables thatdeclare the fields{ }empty class body, nothingextra added
Which parts of the record declaration are the class name and the component list, and what does the empty pair of braces contribute?

Read the strip from left to right. The words public and record come before the class name. FullName names the record class. The parenthesized list holds the instance variables. The empty braces close the class body. To check your reading, ask two questions of any record class definition: what is the name of the class, and which instance variables sit inside the parentheses? If you can answer both, you have read the definition correctly.

Tracing What the Definition Does Before Any Object Exists

Trace the state of the program at the moment the record class definition has been read but no object has been created yet. At this point, the program knows that a kind of object called FullName exists, and that every FullName object will have two String fields named firstName and lastName. The program does not yet hold any first name or last name. No particular FullName object has been made, so no values for those fields exist anywhere.

This is the state that matters most. The definition is a blueprint for objects, not an object. Compare the situation to a form that lists the blanks to be filled in: the form defines which blanks exist, but the blanks stay empty until someone fills them in for a particular person.

Creating a Record Instance with new

A record of type FullName, meaning an instance of the record class, is created in the usual way, with the new operator. The values in the parentheses after the class name are supplied in the same order as the instance variables they correspond to. In the line below, the first value goes to firstName and the second value goes to lastName, which matches the parallel the source draws with a formal parameter list.

java
Notes on the code
  • new FullName(...) creates a new object of type FullName
  • "Ada" is supplied first, so it corresponds to firstName
  • "Lovelace" is supplied second, so it corresponds to lastName
  • name is a variable set up to refer to the new object
Worked example

Reading a FullName creation line step by step

Given the FullName record class and the line FullName name = new FullName("Ada", "Lovelace");, explain what happens in order.

  1. 1
    Step 1: Identify the class

    The class being used is FullName, the record class defined earlier with the instance variables firstName and lastName.

  2. 2
    Step 2: Apply the new operator

    The new operator makes a new object of type FullName. The definition existed before this step, but no particular object existed until now.

  3. 3
    Step 3: Match values to instance variables

    The first supplied value, Ada, goes to firstName. The second supplied value, Lovelace, goes to lastName. The order of the values follows the order of the instance variables in the definition.

  4. 4
    Step 4: Bind the variable

    The variable called name is set up to refer to the new FullName object. The variable does not hold the class definition itself.

Result

A FullName object now exists with firstName holding Ada and lastName holding Lovelace, and the variable name refers to that object.

firstNameAdalastNameLovelace
How does each instance variable name map to the value stored for this particular record object?

The diagram shows the state of the one object created by the line above. Each instance variable name is a key, and the value stored for this particular object is shown beside it. A second FullName object created with different values would have its own separate pair of values, while sharing the same two instance variable names from the class definition.

Record Definition Versus Method Parameter List

The parenthesized list in a record definition looks like a formal parameter list, which is why beginners often confuse them. The source is explicit that the meanings differ. In a record class definition, the list declares fields. It names the data each object of the class will hold. The same shape of text appearing in a method header is a different construct, so the surrounding words and position are what tell you which role it plays.

FeatureRecord class definitionMethod formal parameter list
PositionDirectly after the class nameDirectly after the method name
MeaningDeclares fields, the instance variables of the recordDeclares the inputs the method is written to receive
Example text(String firstName, String lastName)(String firstName, String lastName)
What it createsThe set of instance variables for every object of the record classLocal names used inside the method body

Two lists that look alike but play different roles

Mistakes Beginners Make with Record Definitions

  • Common mistake

    Treating the parenthesized list as a method's parameter list

    What it looks like

    Reading public record FullName(String firstName, String lastName) {} as a method call or method header

    Why it fails

    The list declares the instance variables that are the fields of the record, not inputs to a method.

    Do this instead

    Ask what the class name is and which instance variables sit inside the parentheses. For a record, the parenthesized list names the fields.

  • Common mistake

    Assuming the definition already contains a particular object

    What it looks like

    Believing that FullName already holds the name Ada before any new line runs

    Why it fails

    The definition describes a kind of object. It does not yet contain any particular object.

    Do this instead
    Create an object with the new operator to get a particular instance, such as FullName name = new FullName("Ada", "Lovelace");
  • Common mistake

    Forgetting the empty class body

    What it looks like

    Looking for extra members after the parentheses and missing that the braces are empty

    Why it fails

    The braces enclose a class body that adds nothing beyond the instance variables in this simplest version.

    Do this instead

    Recognize the closing braces as an empty class body, and do not assume extra code is present.

  • Common mistake

    Supplying values in the wrong order when calling new

Practice Reading and Creating Records

EASY

Given the record definition public record FullName(String firstName, String lastName) {}, name the class, list its instance variables with their types, and state whether the empty braces add any extra members. Then write a line that creates a FullName object for a person whose first name is Grace and whose last name is Hopper.

Hints
  • The class name comes first, directly after the keyword record.
  • The instance variables are the entries inside the parentheses, each with a type and a name.
  • Use the new operator, and supply the values in the same order as firstName and lastName.

Key Takeaways

  • A Java record is an object that belongs to a special kind of class called a record class.
  • In the simplest case, a record class specifies only the set of instance variables that represent the fields of the record, and its class body can be empty.
  • A record class definition places the class name first, then lists the instance variables in parentheses, followed by a class body.
  • The parenthesized list looks like a formal parameter list but declares fields, and the definition describes a kind of object rather than a particular object.
  • A particular record object is created with the new operator, and its supplied values line up in order with the instance variables.