🔒 Object-Oriented Programming

Encapsulation & Scope

⏱ 2 hr2 topicsInteractive
🎯 By the end: You can choose the right access specifier, explain who can see a member, and identify a variable's scope (class, instance, argument or local).

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:

SpecifierVisible to
privateOnly inside the same class (most restrictive)
protectedSame class, same package, and subclasses
publicEverywhere (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:

VariableDeclaredLives
Class variable (static)In the class, marked staticOne shared copy for the whole class
Instance variableIn the class, not staticOne copy per object
Argument variableIn a method's parameter listOnly while that method runs
Local variableInside a method/blockOnly 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:

  1. Has a private instance variable balance.
  2. Has public methods deposit(amount) and getBalance().
  3. Uses a static variable to count how many Account objects are created.
  4. 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.