---
title: "Access, Visibility, and Encapsulation | FiveStudy"
description: "The visibility matrix, encapsulation's payoff, accessors/mutators as checkpoints, and a free-response style task."
url: https://fivestudy.com/guides/access-visibility-encapsulation
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Access, Visibility, and Encapsulation

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Class Creation

AP® Computer Science A · Class Creation

# Access, Visibility, and *Encapsulation*

The anatomy of a class, how the keywords public and private control which code can use each part, and why keeping instance variables private, encapsulation, makes classes safer and easier to change.

1. Anatomy of a Class 2. public and private 3. Private Instance Variables 4. Public and Private Methods 5. Why Encapsulate 6. Reading a Class

Big Picture

**Data encapsulation** is a technique in which the implementation details of a class are kept hidden from external classes. The keywords `public` and `private` affect the access of classes, data, constructors, and methods: `private` restricts access to the declaring class, while `public` allows access from classes outside it. Classes and constructors are designated `public`. Instance variables belong to the object, each object having its own copy, and are designated `private` unless a specification says otherwise. Methods may be `public`, for use by other classes, or `private`, for use only inside the class.

## 1 Anatomy of a Class

A class definition begins with a header, `public class Speaker`, followed by a body in braces. Classes written here are always designated `public` and are declared with the keyword `class`. Inside the body come three kinds of members: **instance variables**, which hold each object's attributes; **constructors**, which set up new objects; and **methods**, which define the object's behaviors.

By convention, instance variables are declared first, at the top of the class body and outside every method and constructor, followed by constructors and then methods. Constructors are designated `public`, since other classes must be able to create objects. Reading a class in this order answers three questions in turn: what does each object know, how is it created, and what can it do?

**Figure 1.** A class groups its attributes, constructors, and methods. The keywords `public` and `private` decide which parts other classes may use.

| Part of a class | Usual access | Why |
| --- | --- | --- |
| The class itself | `public class Name` | Other classes need to create and use its objects |
| Constructors | `public` | Other classes must be able to create objects |
| Instance variables | `private` | Keeps attributes internal: encapsulation |
| Methods other classes call | `public` | They form the class's interface |
| Helper methods | `private` | Implementation details used only inside the class |

## 2 public and private

The keywords `public` and `private` are **access modifiers**. The keyword `private` restricts access to the declaring class: a private instance variable or method can be used only by code written inside that same class. The keyword `public` allows access from classes outside the declaring class, so any other class can use the member through an object or the class name.

Access is checked by the compiler. A statement in another class that names a private member does not compile, and the error message says that the member "has private access." This makes access rules a design tool: by choosing which members are public, the author of a class decides exactly how other code is allowed to interact with its objects.

Access is decided per class, not per object. Code inside the `Speaker` class can use the private members of any `Speaker` object, not only the one whose method is running. What private blocks is code written in *other* classes, such as a `Main` class that creates and uses speakers.

**Figure 2.** Private members are usable only inside their own class; public members are usable everywhere.

| Attempt from another class | Result |
| --- | --- |
| `new Speaker("Porch")` | Allowed: public constructor |
| `s.getVolume()` | Allowed: public method |
| `s.volume` | Compile error: volume has private access |
| `s.clamp(42)` | Compile error: clamp has private access |

Worked Example 1 Reading a class

### Classifying Each Member

For the `Speaker` class above, state which members another class may use.

1. 1 **Usable from outside (public):** the constructor `Speaker(String)`, and the methods `getName`, `getVolume`, `setVolume`, and `louder`.
2. 2 **Usable only inside (private):** the instance variables `name` and `volume`, and the helper method `clamp`.
3. 3 **The class itself** is declared `public class Speaker`, so other classes may create and use `Speaker` objects.

**Result:** Other classes can construct speakers and call four methods; everything else is hidden. Listing the public members gives the class's interface, which is all its users need to know.

## 3 Private Instance Variables

Instance variables belong to the object, and each object has its own copy of the variable. A `Speaker` named "Kitchen" and one named "Garage" each store their own `name` and `volume`, and changing one does not affect the other.

Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as `private` unless the class specification states otherwise. Other classes then read and change an object's data only through the methods the class provides, which can check and enforce rules about valid values.

The methods that read and change private data are usually small and predictable: an accessor such as `getVolume` returns a copy of a value, and a mutator such as `setVolume` changes it, applying any rules on the way. A class does not need a mutator for every attribute; leaving one out, as `Speaker` does for `name`, makes that attribute unchangeable from outside once the object is created.

**Figure 3.** The keyword `private` restricts access to the declaring class, while `public` allows access from classes outside it.

Worked Example 2 Each object has its own copy

### Two Speakers, Two Volumes

Predict the output.

Using the same Speaker class

```
public class Speaker
{
    private String name;
    private int volume;

    public Speaker(String n)
    {
        name = n;
        volume = 5;
    }

    public String getName()
    {
        return name;
    }

    public int getVolume()
    {
        return volume;
    }

    public void setVolume(int v)
    {
        volume = clamp(v);
    }

    public void louder()
    {
        setVolume(volume + 1);
    }

    private int clamp(int v)
    {
        if (v < 0)
        {
            return 0;
        }
        if (v > 10)
        {
            return 10;
        }
        return v;
    }
}
```

Output

```
Kitchen 9
Garage 6
```

1. 1 **Instance variables belong to the object.** `a` and `b` each have their own `name` and `volume`.
2. 2 **`a.setVolume(9)`** affects only `a`; `b.louder()` raises only `b` from 5 to 6.

**Result:** The output is Kitchen 9 and Garage 6. Each object has its own copy of every instance variable, and private access does not change that: it limits who can reach the data, not how many copies exist.

Worked Example 3 private instance variables

### Reaching Past the Methods

Explain the compile error.

Code that does not compile

```
public class Speaker
{
    private String name;
    private int volume;

    public Speaker(String n)
    {
        name = n;
        volume = 5;
    }

    public String getName()
    {
        return name;
    }

    public int getVolume()
    {
        return volume;
    }

    public void setVolume(int v)
    {
        volume = clamp(v);
    }

    public void louder()
    {
        setVolume(volume + 1);
    }

    private int clamp(int v)
    {
        if (v < 0)
        {
            return 0;
        }
        if (v > 10)
        {
            return 10;
        }
        return v;
    }
}
```

1. 1 **`volume` is private.** It can be used only inside the `Speaker` class.
2. 2 **Main is another class,** so the compiler reports that `volume` has private access in `Speaker`.
3. 3 **Fix.** Use the public method: `s.setVolume(15);`, which also applies the 0-to-10 rule.

**Result:** The code does not compile. Making instance variables private forces every change through the class's methods, which is what lets the class protect its data.

Common Mistake 1 · Making Instance Variables public

A `public` instance variable lets any class set it to anything, including values that break the object's rules, such as a volume of 15 or −3. Keep instance variables `private` and provide methods that change them safely.

## 4 Public and Private Methods

Access to behaviors can be internal or external to the class. Methods designated as `public` can be accessed internally or externally to a class, whereas methods designated as `private` can only be accessed internally to the class. Public methods form the class's **interface**, the set of operations other code relies on.

Private methods are helpers. When a public method contains a step that is useful on its own, or that several methods share, the step can be extracted into a private method, such as `clamp`. Because no other class can call it, a private helper can be changed, renamed, or removed freely, as long as the public methods still behave the same.

Worked Example 4 Using public members

### Working Through the Public Interface

The `Speaker` class is given. Predict the output.

The Speaker class and a short program

```
public class Speaker
{
    private String name;
    private int volume;

    public Speaker(String n)
    {
        name = n;
        volume = 5;
    }

    public String getName()
    {
        return name;
    }

    public int getVolume()
    {
        return volume;
    }

    public void setVolume(int v)
    {
        volume = clamp(v);
    }

    public void louder()
    {
        setVolume(volume + 1);
    }

    private int clamp(int v)
    {
        if (v < 0)
        {
            return 0;
        }
        if (v > 10)
        {
            return 10;
        }
        return v;
    }
}
```

Output

```
Porch 7
10
0
```

1. 1 **Constructor.** Volume starts at 5; two calls to `louder` raise it to 7.
2. 2 **`setVolume(15)`.** The private helper `clamp` limits it to 10.
3. 3 **`setVolume(-3)`.** Clamped to 0.
4. 4 **Main never touches `volume` directly;** every change goes through public methods.

**Result:** The output is Porch 7, 10, 0. Outside code uses only the public constructor and methods, and the class keeps its volume between 0 and 10 no matter what values are requested.

Worked Example 5 private methods

### A Helper Only the Class May Call

Explain the compile error.

Code that does not compile

```
public class Speaker
{
    private String name;
    private int volume;

    public Speaker(String n)
    {
        name = n;
        volume = 5;
    }

    public String getName()
    {
        return name;
    }

    public int getVolume()
    {
        return volume;
    }

    public void setVolume(int v)
    {
        volume = clamp(v);
    }

    public void louder()
    {
        setVolume(volume + 1);
    }

    private int clamp(int v)
    {
        if (v < 0)
        {
            return 0;
        }
        if (v > 10)
        {
            return 10;
        }
        return v;
    }
}
```

1. 1 **`clamp` is private.** `setVolume` calls it internally, but other classes cannot.
2. 2 **Why private.** `clamp` is an implementation detail; keeping it private means it can be changed or removed without affecting any other class.

**Result:** The call does not compile. Methods designated as private can only be accessed internally to the class, while public methods can be accessed internally or externally.

Common Mistake 2 · Calling a Private Helper From Another Class

A private method is invisible outside its class. If code in another class needs that behavior, the class should offer a public method that provides it, usually one that uses the helper internally.

## 5 Why Encapsulate?

Encapsulation means that a class's implementation details, its instance variables and helper methods, are kept hidden from external classes. Two benefits follow. First, the class can guarantee that its objects are always valid, because every change passes through its own methods. Second, the class's author can change how the class works internally without breaking other code, as long as the public methods keep their signatures and behavior.

Encapsulation also makes programs easier to understand and debug. Users of a class need to learn only its public methods, and if an object's data is ever wrong, the cause must be in the class's own code, because nothing else could have changed it. These benefits grow with the size of the program and the number of people working on it.

**Figure 4.** Data encapsulation keeps a class's implementation details hidden. Because `volume` is private, every change goes through methods that keep it valid.

| Benefit of encapsulation | Example |
| --- | --- |
| Protects valid state | Volume always stays between 0 and 10 |
| Allows internal changes | Rewrite a private helper without touching other classes |
| Simplifies use | Users learn a few public methods, not the internals |
| Localizes errors | Only the class's own code can change its data |

Worked Example 6 Encapsulation and change

### Changing the Inside Without Breaking the Outside

The class's author replaces the private helper with a different implementation. Does the calling code need to change?

A Dial class with a private helper

```
public class Dial
{
    private int level;

    public Dial()
    {
        level = 0;
    }

    public void turn(int steps)
    {
        level = wrap(level + steps);
    }

    public int getLevel()
    {
        return level;
    }

    private int wrap(int v)
    {
        return v % 12;
    }
}
```

Output

```
2
```

1. 1 **The public interface** is just `turn` and `getLevel`.
2. 2 **Trace.** 0 + 5 = 5; then 5 + 9 = 14, and `14 % 12` = 2.
3. 3 **Freedom to change.** Because `wrap` and `level` are private, the author could store the level differently or rewrite `wrap` entirely; as long as `turn` and `getLevel` behave the same, no other class needs to change.

**Result:** The program prints 2, and callers never depend on how it was computed. Encapsulation keeps implementation details hidden from external classes, so they can change safely.

Common Mistake 3 · Exposing Internals Through Method Names

Encapsulation is about what users depend on. A public method named for an internal detail, such as `getClampResult`, ties other code to how the class works. Name public methods for what they do for the user, such as `setVolume`.

## 6 Reading and Writing Classes

When reading a class, start with its public members: they say what the class offers. Then read the private instance variables to see what each object stores, and finally the method bodies to see how the behaviors work. When writing a class, follow the conventions in this guide: a `public` class, `public` constructors, `private` instance variables, `public` methods for the interface, and `private` helper methods for internal steps.

Access modifiers apply to members of a class. Local variables declared inside a method or constructor, including parameters, never take `public` or `private`; they exist only while the method runs and are already invisible to every other class.

Common Mistake 4 · Adding an Access Modifier to a Local Variable

`private int total = 0;` written inside a method does not compile. Only class members, meaning instance variables, class variables, constructors, and methods, take access modifiers. Local variables are declared with just a type and a name.

### Four Habits for Encapsulated Classes

#### 1. public Class, public Constructors

So other classes can create objects.

#### 2. private Instance Variables

Change data only through methods.

#### 3. public Interface, private Helpers

Expose what users need; hide the rest.

#### 4. Each Object, Its Own Copy

Private limits access, not the number of copies.

Core Synthesis

Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords `public` and `private` affect the access of classes, data, constructors, and methods: `private` restricts access to the declaring class, while `public` allows access from classes outside it. Classes are designated `public` and declared with the keyword `class`, and constructors are designated `public`. Instance variables belong to the object, each object having its own copy, and should be designated `private` unless the class specification states otherwise. Public methods can be accessed internally or externally to a class, whereas private methods can only be accessed internally.

FiveStudy AP® Computer Science A Study Guide · Class Creation · Access, Visibility, and Encapsulation Back to top ↑
