Writing a class
Java for AP CS A Lesson 6 2:02 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Until now you have used other people's types.
到目前为止你用的都是别人写好的类型。
Now you make your own.
现在你要造自己的。
A class is a blueprint: it says what a Dog HAS — a name and an age.
类是一张蓝图:它说明一条 Dog "有"什么——一个名字和一个年龄。
Those are its instance variables, or fields.
这些就是它的实例变量,也叫字段。
But the class is not a dog.
但类本身并不是一条狗。
From this one blueprint you can make as many dogs as you like, and each one has its own values.
从这一张蓝图,你想造多少条狗就造多少条, 而每一条都有它自己的值。
Every object gets its own copy of every field.
每个对象都拿到属于自己的一份字段。
A constructor is what runs when you write new.
构造器就是你写 new 时运行的那段代码。
It takes the values you hand it and fills in the fields of the object being built — so new Dog of Rex and three gives you an object with those values already in place.
它接过你传给它的值, 把正在建造的这个对象的字段填好—— 所以 new Dog("Rex", 3) 交给你的对象,值已经在里面了。
Two rules the exam checks: a constructor has the same name as the class, and it has no return type at all.
有两条规则考试会查: 构造器和类同名,而且它完全没有返回类型。
Not even void.
连 void 都没有。
Look at that assignment closely, because both sides say name.
仔细看那一句赋值,因为两边都写着 name。
They are two different boxes: on the left is the object's own field, and on the right is the parameter that was just passed in.
它们是两个不同的盒子: 左边是这个对象自己的字段, 右边是刚刚传进来的那个参数。
The word this is what says which one you mean — this dot name is the object's own.
this 这个词,就是用来说明你指的是哪一个—— this.name 指的是这个对象自己的那一个。
An instance method is a thing the object can DO, and because it belongs to an object you call it on an object: rex dot bark, then bo dot bark.
实例方法是这个对象"能做"的事, 而因为它属于某个对象,你要在对象上调用它: rex.bark(),然后 bo.bark()。
Same method, written once — but each call reads the field of the object it was called on, so you get Rex says woof and then Bo says woof.
同一个方法,只写了一遍—— 但每次调用读的都是"被调用的那个对象"的字段, 于是你先得到 Rex says woof,再得到 Bo says woof。
Four things to take with you.
带走四点。
One: a class is a blueprint, and an object is built from it.
第一:类是蓝图,对象是照着它造出来的。
Two: the constructor runs when you write new.
第二:构造器在你写 new 的时候运行。
Three: it has the class's name and no return type.
第三:它和类同名,而且没有返回类型。
Four: this dot name means this object's own field.
第四:this.name 指的是这个对象自己的字段。
Now write a class in the task below.
现在去下面的题里写一个类。