Junior — Middle
What is the purpose of classes in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, a class is a template or blueprint for creating objects. It describes the properties (fields) and behaviors (methods) that objects of this type will have.
Purpose of classes:
- Encapsulation of data and logic — combining state and behavior in one place.
- Code reuse — multiple objects can be created based on a single class.
- Abstraction — hiding implementation details while providing a clear interface.
- Modeling real-world entities — classes help structure the program by reflecting the subject area.
Example:
public class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public void drive() {
System.out.println(model + " is driving");
}
}
Here, the Car class describes what a car is, what properties it has, and what it can do.