CHAPTER 33 — Encapsulation

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to home page   go to next page

created 12/13/98; revised: 09/23/99, 01/21/00, 07/14/02, 01/19/06, 11/11/08

CHAPTER 33 — Encapsulation

So far, the objects that we have designed have instance variables that are visible outside of the objects. Code that holds a reference to an object can change the object's instance variables. This can lead to problems.

A better design enforces encapsulation. Some (or all) of an object's instance variables are visible only to the object's own methods. Code outside of the object cannot access these variables directly. This chapter discusses how to use the private visibility modifier to do this.

Chapter Topics:

  • The private and the public visibility modifiers
  • Default visibility
  • Encapsulation
  • Access methods
  • Enhancement of the CheckingAccount class

QUESTION 1:

Should a bank control who has access to your checking account?