Lesson 84: Classes and objects
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
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.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
เลข class Light describes any LED: its attributes are pin และ timesOn, and its methods are what it can do. red และ green are two objects of the class. Write the methods on และ off; on also adds 1 to timesOn. Then the two LEDs take turns.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The program wants to print how often the red light was on, but timesOn เป็น 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.
คลิก Run เพื่อดูผลลัพธ์ที่นี่