Classes and OOP
Object-oriented programming (OOP) organises code around objects that bundle data (properties) and behaviour (methods). A class is a blueprint for creating many similar objects.
Defining a class
constructorruns automatically when you callnew Product(...).thisrefers to the specific object being created or used.- Methods are shared by all instances, so they aren't copied into each one.
Inheritance with extends
A class can extend another and reuse its code. Call super(...) to run the parent's constructor.
Private fields, getters and setters
Fields that start with # are truly private: code outside the class can't read them.
Composition over inheritance
Deep inheritance trees become hard to change. Pros often prefer composition: building objects out of smaller pieces.
The four OOP pillars, briefly
| Pillar | Meaning | In JS |
|---|---|---|
| Encapsulation | Hide internal details | #private fields, closures |
| Abstraction | Expose a simple interface | Public methods like deposit() |
| Inheritance | Reuse a parent's behaviour | extends, super |
| Polymorphism | Same method, different behaviour | Overriding speak() |
Practice
Create a Shape class with an area() method that returns 0, and subclasses Circle(radius) and Rectangle(w, h) that override it. Then print the total area of an array of shapes.
1.What must a subclass constructor call before using this?
2.How do you make a truly private field in a JavaScript class?