Junior
What are classes in the context of object-oriented programming?
sobes.tech AI
Answer from AI
A class in OOP (object-oriented programming) is a template or blueprint for creating objects.
It defines:
- State (properties or fields): Data stored in objects of this class.
- Behavior (methods): Functions or actions that objects of this class can perform.
A class allows creating multiple objects of the same type with the same structure of properties and set of methods, but with unique property values. Instantiating a class creates an object that is an instance of this class.
Example:
// Definition of the Car class
class Car {
// Constructor - method called when creating a new object
constructor(brand, model, year) {
this.brand = brand; // Property
this.model = model; // Property
this.year = year; // Property
}
// Method
startEngine() {
console.log(`${this.brand} ${this.model} engine started.`);
}
}
// Creating objects (instances) of the Car class
const myCar = new Car("Toyota", "Camry", 2022);
const partnerCar = new Car("Honda", "Civic", 2023);
// Using object methods
myCar.startEngine();
partnerCar.startEngine();
// Accessing object properties
console.log(myCar.brand);
console.log(partnerCar.year);