Encapsulation
Java for AP CS A Lesson 7 1:54 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Encapsulation means hiding an object's data and only changing it through methods.
封装的意思是把对象的数据藏起来,只允许通过方法去改动它。
Mark a field private and outside code cannot touch it — the direct route is closed.
把一个字段标成 private,外面的代码就碰不到它了—— 直通的那条路被关上了。
The only way in is through a method you wrote and made public.
唯一的入口,是一个你自己写的、标成 public 的方法。
That sounds like extra work for nothing, but it is the whole point, and the next beat shows why.
这听起来像是白费功夫, 但它恰恰是关键所在,下一段就说明为什么。
An accessor, or getter, reads the field and hands it back.
访问器(getter)读取字段并把它交出来。
A mutator, or setter, changes it — and because it is a method, it can look at what it was given first.
修改器(setter)负责改动它—— 而因为它是一个方法,它可以先看一眼别人给了什么。
Deposit fifty is allowed.
存入 50,允许。
Deposit minus five hundred is refused, and nothing changes.
存入 -500,被拒绝,什么都不变。
A public field could never refuse a bad value; a method is the only place that rule can live.
一个公开的字段永远没法拒绝一个坏值; 方法是那条规则唯一能待的地方。
Next, a counting question.
接下来是一个"数数"的问题。
An instance variable gets one copy per object — three accounts, three separate balances.
实例变量是每个对象一份—— 三个账户,就有三个各自独立的余额。
A static variable is different: there is one copy for the whole class, shared by all of them.
静态变量不一样:整个类只有一份,所有对象共用它。
A count of how many accounts exist belongs to the class, not to any one account.
"一共开了多少个账户"这个数字属于类, 而不属于其中任何一个账户。
Last, printing.
最后是打印。
Print an object with no toString and you get the class name and a memory address, which helps nobody.
如果没有写 toString,打印一个对象得到的是类名加一串内存地址, 对谁都没用。
Write a toString that returns something readable, and println uses it automatically — no change at the call site at all.
写一个 toString,让它返回一句人能读懂的话, println 就会自动用它—— 调用那一端一个字都不用改。
Four things to take with you.
带走四点。
One: private stops outside code touching a field.
第一:private 让外面的代码碰不到字段。
Two: a getter reads it, and a setter changes it.
第二:getter 读它,setter 改它。
Three: the setter is the only place a rule can live.
第三:setter 是规则唯一能待的地方。
Four: static means one copy for the whole class.
第四:static 意味着整个类只有一份。
Now encapsulate a class in the task below.
现在去下面的题里给一个类做封装。