Lesson 84: Classes and objects
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.)
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.
Dificultad 4/5 · 280 monedas + un pequeño bono en el primer intento de hoy
El class Light describes any LED: its attributes are pin y timesOn, and its methods are what it can do. red y green are two objects of the class. Write the methods on y off; on also adds 1 to timesOn. Then the two LEDs take turns.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
The program wants to print how often the red light was on, but timesOn es 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.
Haz clic en Ejecutar para ver la salida aquí.