Concepts / Static and Non-Static Members in Classes

Static and Non-Static Members in Classes

A class is a blueprint, or factory, used to construct objects; it describes what objects will contain rather than being the objects themselves

  • Programming

Two Players, One Class

By now you have written classes that hold variables and methods, which in this course are called subroutines. An object is built from those same ingredients: it is also a collection of variables and methods. That raises a natural question. If an object looks like its class, how is it different from the class it comes from? The answer matters because it changes how you reason about code. When a program creates many objects from one class, and creates and discards them while it runs, the difference between the class and its objects stops being a technicality and becomes the key to predicting what your program does.

What do you think happens?

Suppose a and b are both created from the same Player class. Then a.score is set to 10. What is b.score?

  • 10

  • 0

  • It is undefined

Reveal answer
Answer:

0

Each object gets its own copy of the non-static variable score. Setting a.score changes only the copy that belongs to a. The object b has a separate copy, which still holds 0.

Tracing Two Objects Side by Side

The prediction above depends on one idea: the non-static variables of a class are not shared. Each object created from the class has its own set of those variables. The code below defines a small Player class with one non-static variable, score, and creates two objects from it.

java
Output
10
0
Notes on the code
  • score is declared inside the class but outside any method, so every object built from Player will contain one
  • new Player() constructs a fresh object, and each call produces its own separate score
  • Changing a.score updates only object a; object b is untouched
a.score10b.score0
After a.score is set to 10, what value does b.score hold, and why does it not change?

The diagram shows the result of the trace. The score box for object a has changed to 10, and the score box for object b still holds 0. Each object is a separate item with its own values, so a change to one leaves the other alone. Notice that the diagram does not show a single score box that both objects read from.

The Class as a Blueprint

Definition

A class is a blueprint, or factory, used to construct objects. It describes what objects will contain rather than being the objects themselves.

In the real world

A blueprint for a house does not contain a house, and it does not live in a neighborhood. It specifies what the house will have: its rooms, its doors, and where the walls go. Each house built from that blueprint has the same layout, yet each is a separate building that can be painted a different color or furnished differently. A class plays the same role. The Player class above is the description; the objects a and b are the separate things the description produces.

Player classdescription of structureObject ascore: 10Object bscore: 0new Player()new Player()
Which part is the blueprint, and which parts are the objects built from it?

The class sits at the top of the picture because it is the plan. The two objects sit below it because they are the products. The class does not hold a score for the program to use; it holds the description of what a score is for each Player. Only when the program asks for an object does that structure become a real, separate item with real values.

Where the Non-Static Parts Fit

The description inside a class is split into parts. The non-static parts are the ones that matter for building objects. They specify which variables and methods each object will contain. In the Player example, the variable score and the method addPoints are non-static parts. Every object created from Player contains both of them. When a source says that the non-static portions of a class describe objects, this is what it means: those portions set out the structure that each object will have.

Code walkthrough
class Team {
    String name = "Unnamed";
    int wins = 0;

    void recordWin() {
        wins = wins + 1;
    }
}

Team red = new Team();
Team blue = new Team();
red.recordWin();
red.recordWin();
blue.recordWin();
  1. 1
    Line 1 declares the class Team. Nothing is built yet, so no team exists in memory.
  2. 2
    Lines 2 and 3 declare the non-static variables that every Team will contain.
  3. 3
    Lines 5 to 7 declare the non-static method that every Team will contain.
  4. 4
    The statement Team red = new Team() asks the class to construct an object with that structure.
  5. 5
    The statement Team blue = new Team() constructs a second, separate object from the same description.
  6. 6
    The two recordWin calls on red change only red's wins; the single call on blue changes only blue's wins.
  • name and wins are non-static variables; each Team object gets its own pair
  • recordWin is a non-static method; each Team object carries its own copy of it
  • After these calls, red.wins is 2 and blue.wins is 1, because each object counts its own wins

How the Program Builds and Discards Objects

The source stresses that objects are created and destroyed as the program runs. The class, by contrast, is the description that stays in place. You can think of the class as a fixed plan that exists before the program does anything interesting, and the objects as temporary products that appear when the program asks for them and disappear when they are no longer needed. The same class can produce many objects over the lifetime of one program, and those objects do not all need to exist at the same moment. The before and after pair below shows this change of state.

Before
class Player {
    int score = 0;
}
// The class exists as a description.
// No Player object has been built yet.

Only the class description exists. No objects with score values exist.

After
class Player {
    int score = 0;
}
Player a = new Player();
Player b = new Player();
// Two separate objects now exist, each with its own score.

Two objects exist, each containing its own score. The class description is unchanged.

Notice what the transition did not change. The class Player is exactly the same text before and after. Creating objects did not edit the blueprint. It produced two new items that follow the blueprint's structure. This is why the source describes the class as the thing that stays in place, while objects come and go while the program runs.

Static Members as the Contrast

This article focuses on the non-static parts of a class, because they are what determine the structure of each object. The contrast with static members is the other half of the picture. A static member is not part of each object's own structure in the way a non-static member is. The comparison below sets the two kinds of member side by side so you can see where each one exists.

Static memberone copy for the wholeclassNon-static memberone separate copy in eachobject
Where does each kind of member exist: once for the whole class, or separately in each object?

Mistakes Beginners Make with Objects and Classes

  • Common mistake

    Treating the class and an object as the same thing

    What it looks like

    Believing that Player.score can be read the way a.score can, as if the class itself held a score for each player.

    Why it fails

    The class is the description. The objects are the products that carry values. A non-static variable such as score exists inside each object, not in the class description.

    Do this instead

    Ask whether you are talking about the plan or about a built item. Values belong to objects; the class describes what those values will be.

  • Common mistake

    Assuming that objects belong to a class the way a part belongs to a whole

    What it looks like

    Saying that object a is a piece of the Player class, as a wheel is a piece of a car.

    Why it fails

    The word belong suggests ownership of a part. What actually happens is construction: the class helps produce a new, separate item.

    Do this instead

    Describe the relationship as construction. The class produces objects; the objects are separate things that follow the description.

  • Common mistake

    Expecting one object's changes to appear in another

    What it looks like

    Setting a.score to 10 and then expecting b.score to read 10 as well.

    Why it fails

    Each object has its own copy of the non-static variables, so changing one copy leaves the others unchanged.

    Do this instead

    Track each object by name. Update a.score for object a and b.score for object b, and check each one separately.

  • Common mistake

    Forgetting that new is needed to build an object, so that a class name alone does not give you an object to work with

Practice: Predicting Object State

EASY

A class Book has the non-static variable pages and the non-static method readPages. Two objects are created: first = new Book() and second = new Book(). Then first.pages is set to 300, and second.pages is set to 120. What does first.pages contain after the second assignment, and which part of the program's structure makes this possible?

Hints
  • Ask whether pages lives in the class description or in each object.
  • Think about whether setting second.pages could change the copy that belongs to first.
  • Remember that the class is the blueprint and the two objects are separate products.
MEDIUM

Without running code, list the non-static parts that every object created from a class Book would contain, given a class that declares the variables title and pages and the method readPages. Then state whether creating a third Book object would change the first two.

Hints
  • Each non-static variable and method declared in the class description appears in every object.
  • Creating a new object constructs a new item; it does not edit the existing ones.

Key Takeaways

  • A class is a blueprint, or factory, that describes what objects will contain; it is not itself the objects.
  • The non-static parts of a class specify the variables and methods that every object created from that class will contain.
  • Each object is a separate item with its own values, so changing one object's non-static variables leaves other objects unchanged.
  • The class is the description that stays in place, while objects are created and destroyed as the program runs.
  • Static members are the contrast case, and this article's explanations focus on the non-static parts that define each object's structure.