Skip Top Navigation Bar

Class Anatomy

Data Encapsulation

Data encapsulation is the practice of keeping an object's data together with the methods that work with that data. It also allows a class to control how its data is accessed and modified.

One way Java supports encapsulation is through access modifiers, such as public and private.

Using encapsulation helps protect an object's data and makes classes easier to maintain.


Access Modifiers

An access modifier determines where a class, field, constructor, or method can be accessed.

The two most common access modifiers are:

In AP CSA, it is recommended to use private for:

In AP CSA, it is recommended to use public for:

Benefits of Encapsulation

Encapsulation helps you:

By controlling how data is accessed, you can change the implementation of a class without affecting the code that uses it.

Choosing Between public and private

As a general guideline:

This approach helps keep objects in a valid state while providing a clear interface for interacting with them.