Lesson 84: Classes and objects
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
English
One class, many objects
- A class is a plan for objects: it lists their attributes (data) and methods (what they can do).
- An object is one thing made from the class.
Light red(12);makes an object and runs the constructor, which sets its attributes. - Private attributes can only be used by the class's own methods. A getter is a public method that returns one of them.
| OOP word | In this lesson |
|---|---|
| class | Light |
| objects | red, green |
| attributes | pin, timesOn (private) |
| methods | begin, on, off, getTimesOn |
- Write the methods below the class, like
void Light::on() { ... }. (If you write a method's body inside the class, this simulator's compiler step does not accept it.)
English
In the exam
- 9618/32/M/J/23 Q4: match OOP terms to descriptions. Mark scheme: encapsulation is the process of putting data and methods together as a single unit; getters are methods used to return the value of a property; setters are methods used to update it.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The class Light describes any LED: its attributes are pin và timesOn, and its methods are what it can do. red và green are two objects of the class. Write the methods on và off; on also adds 1 to timesOn. Then the two LEDs take turns.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The program wants to print how often the red light was on, but timesOn là (is) private: code outside the class cannot read it, so red.timesOn does not compile. Add a public getter method, int getTimesOn(), that returns timesOn, and use red.getTimesOn() in the print.
Nhấn Chạy để xem kết quả ở đây.