Encapsulation means keeping an object's data safe by controlling who can reach it. Java does this with access specifiers. Closely related is scope — where in a program a variable can be used.
1Access specifiers & visibility
An access specifier sets how visible a member (variable or method) is to other code:
| Specifier | Visible to |
|---|---|
private | Only inside the same class (most restrictive) |
protected | Same class, same package, and subclasses |
public | Everywhere (least restrictive) |
class Account {
private double balance; // hidden from outside
public void deposit(double a) { balance += a; } // open
}The encapsulation rule of thumb: make data private, and provide public methods to use it safely. That stops other code from putting the object into a bad state.
Key points
- Access specifiers set visibility: private (same class only), protected (class/package/subclasses), public (everywhere).
- private is most restrictive; public is least restrictive.
- Good encapsulation: keep data private and expose public methods to use it safely.
2Scope of variables
The scope of a variable is the region of the program where it can be used. Java has four kinds:
| Variable | Declared | Lives |
|---|---|---|
| Class variable (static) | In the class, marked static | One shared copy for the whole class |
| Instance variable | In the class, not static | One copy per object |
| Argument variable | In a method's parameter list | Only while that method runs |
| Local variable | Inside a method/block | Only inside that block |
class Demo {
static int count; // class variable (shared)
int id; // instance variable (per object)
void set(int n) { // n is an argument variable
int temp = n * 2; // temp is a local variable
id = temp;
}
}
Key points
- Class (static) variables have one shared copy for the whole class.
- Instance variables have a separate copy in each object.
- Argument variables exist only during a method call; local variables exist only inside their block.
★ Practical: encapsulate a balance
In BlueJ, write a class Account that:
- Has a private instance variable balance.
- Has public methods deposit(amount) and getBalance().
- Uses a static variable to count how many Account objects are created.
- Identify one argument variable and one local variable in your code.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.