Anatomy of a Class
| English | Chinese | Pinyin |
|---|---|---|
| instance variables | 实例变量 | shí lì biàn liàng |
| encapsulation | 封装 | fēng zhuāng |
The three parts of a class
- A class bundles three kinds of members:
- Instance variables — the data (state) each object holds.
- Constructors — set up a new object when it's created.
- Methods — the behaviors the object can perform.
- Data and behavior live together in one place.
Instance variables hold state
- Instance variables 实例变量 store each object's own state.
private String name; private int score;— declared inside the class, outside any method.- Every object gets its own copy — one student's
scoreis separate from another's. - These persist for the life of the object (unlike local variables).
private and public
- Access modifiers control who can reach a member.
private— usable only inside the class;public— usable from anywhere.- Instance variables are usually
private; methods that form the interface arepublic. - This hiding of internal data is called encapsulation 封装.
Why keep data private
- Encapsulation protects an object's data from careless outside changes.
- Outsiders interact only through public methods, which can validate and control access.
- You could reject a negative score in a method; a public variable has no such guard.
- Private data + public methods is the standard, safe class design.
Keep instance variables private; expose behavior through public methods. A public field lets any code set it to anything (a negative score, a null name) with no checks. Encapsulation funnels all access through methods that can validate the change. And each object has its own copy of the instance variables — they're not shared.
Anatomy of a Student class:
- Instance variables:
private String name; private int score; - Constructor:
public Student(String n) { ... } - Methods:
public void addScore(int s) { ... },public int getScore() { ... }
A class has instance variables (each object's state), constructors (set up new objects), and methods (behaviors). Instance variables are usually private and accessed through public methods — this encapsulation protects the data. Each object holds its own copy of the instance variables.
Each object has its own state
a.score and b.score are separate — each object owns its state.
Which are the three kinds of members in a class?
State (instance variables), setup (constructors), behavior (methods).
Instance variables are usually declared...
Private data + public methods = encapsulation.
Keeping data private and exposing it only through methods is called ___ (one word).
Encapsulation protects an object's data.
Two objects of the same class share one copy of each instance variable.
Each object has its own copy of the instance variables.
A private member can be used...
private limits access to inside the class; public opens it up.