Concepts / Classes and Member Variables

Classes and Member Variables

Access control determines the visibility and usability of a class member.

  • Programming

The Central Question

When you write a class, you store data inside it. Some of that data should be protected, meaning that only the class itself should decide how it is read and changed. But other parts of a program often still need to know what the value is. That tension is the starting point for this article: if a value should stay protected inside a class, how can other parts of a program still learn what that value is?

Before reading on, make a prediction. Suppose a class has a private member variable, and a second class holds an object of the first class. Can the second class read that private variable directly by using its name?

What do you think happens?

Can another class read a private member variable directly by its name?

  • Yes, because the other class holds an object of the class

  • No, because a private member can only be used within the class where it is defined

Reveal answer
Answer:

No. A private member can only be used within the class where it is defined, so the other class cannot touch it directly.

The class alone decides how its private data is read and changed. Other classes must go through a route the class provides, such as a public accessor method.

What Access Control Decides

When you write a new class, you have to decide who is allowed to use each of its members. A member is any variable or method that belongs to the class. The decision about who may use each member is called access control, and access control determines the visibility and usability of each member.

Visibility and usability are the two things access control shapes. A member that is visible everywhere is easy to reach, but it is also easy to misuse. A member that is hidden is harder to reach, but its behavior stays under the control of the class that owns it. Access control is therefore a trade-off between convenience and control.

Access controlClass membervariable or methodVisibilitywhere the member can beseenPublicusable from anywhereUsabilityhow the member can be usedPrivateusable only in its ownclassdecides for eachdeterminesdetermineswide when publicnarrow when private
What does a class boundary allow in and keep out, and how do access modifiers mark the line between visible and hidden members?

Public and Private by Location

The two visibility choices differ mainly in where the member can be used. A public member can be used from anywhere, including from other classes. A private member can be used only inside the class where it is defined. Nothing outside that class can touch it directly.

Defining classcan useDefining classcan useOther classescan useOther classescannot use directly
Which code locations can use a public member, and which can use a private member?
PropertyPublic memberPrivate member
Where it can be usedFrom anywhere, including other classesOnly inside the class where it is defined
Can another class use it directlyYesNo
Who decides how its data is read and changedShared by design, so it is easy to reach and easy to misuseThe owning class alone
Typical use for a data variableRarely the first choice for dataThe usual choice, as many programmers prefer

Public and private members compared by where they can be used

Why Many Programmers Make Members Private

Many programmers prefer declaring almost all member variables private, so that the class keeps complete control over them. When a variable is private, the class decides every operation that touches it. Private members are used to encapsulate data and behavior, which means keeping them packaged inside the class that owns them.

Tracing a Private Value Through an Accessor

Even though a variable is private, the owning class can allow other classes to learn its value. It does this by providing a public accessor method that returns the variable. An accessor method is a public method that returns the value of a private variable. The private variable stays hidden, and the public method becomes the single point through which the value leaves the class. Because the class writes that method, it decides what is shared.

The source describes a class with a private member variable named title of type String, and a public method that returns it. The following class is an original illustration of that pattern, written in Java to match the source's terminology. The variable is declared private, and the method getTitle is declared public.

Code walkthrough
public class Book {
    private String title;

    public Book(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}
  1. 1
    The class Book declares one member variable, title, marked private, so only code inside Book can use it directly.
  2. 2
    The constructor receives a title and stores it in the private variable.
  3. 3
    The method getTitle is marked public, so any other class can call it.
  4. 4
    Inside getTitle, the return statement reads the private title and hands its value back to the caller.
  • private String title: the member variable is hidden from other classes
  • public String getTitle(): the public accessor method that exposes the value
  • return title: the accessor reads the private variable on behalf of the caller
java
Output
name now holds the value stored in the private title variable
Other classasks for the titlegetTitlepublic accessortitleprivate Stringcallsreadsvaluereturns value
How does code in another class read a private variable's value when it cannot touch the variable directly, and how does the accessor pass that value across the class boundary?

The diagram shows the only route the value takes. The other class never reaches the private variable directly. It asks the public accessor, and the accessor reads the private variable on its behalf. Only the owning class decides whether that route exists. If the class chose not to write getTitle, no other class could learn the title through this route at all.

Mistakes When Reading Private Members

  • Common mistake

    Assuming a private variable can be read from another class by its name

    What it looks like
    String name = book.title; written in a different class
    Why it fails

    A private member can only be used within the class where it is defined.

    Do this instead

    Call the public accessor instead, such as book.getTitle().

  • Common mistake

    Assuming a public method is required before any value can be shared

    What it looks like

    Making title public just so another class can read it

    Why it fails

    Making the variable public removes the class's control over how it is read and changed, which is the reason many programmers keep members private.

    Do this instead

    Keep the variable private and expose only the value through an accessor method the class writes.

  • Common mistake

    Thinking an accessor gives the other class control over the variable

    Why it fails

    The accessor returns the value through a route the class chose. The class still decides what is shared.

    Do this instead

    Treat the accessor as the one controlled exit point for the value.

Practice Deciding Visibility

MEDIUM

A class Account stores a private member variable named balance. A second class Report needs to show the balance on screen. Without making balance public, describe the route Report should use to learn the balance, and explain which class decides whether that route exists.

Hints
  • Recall that a private member can only be used within the class where it is defined.
  • Think about which public method the Account class would write to expose the value.
  • The owning class is the one that writes the method, so it decides what is shared.

Key Takeaways

  • Access control determines the visibility and usability of each class member, and you decide it when you write the class.
  • A public member can be used from anywhere, including other classes, while a private member can only be used within the class where it is defined.
  • Many programmers declare almost all member variables private so the class keeps complete control over how they are used.
  • An accessor method is a public method that returns the value of a private variable, letting other classes learn the value through a route the class controls.