Junior — Middle
Can you explain the main differences between a class and an object in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming:
-
Class is a template or description of an entity that defines properties (fields) and behavior (methods). A class can be thought of as a blueprint.
-
Object is a specific instance of a class created in memory during program execution. An object has a state defined by the values of its fields.
For example, if a class is "Car," then an object is a specific car with a certain color, make, and license plate.
class Car {
var color: String
init(color: String) {
self.color = color
}
func drive() {
print("The car is driving")
}
}
let myCar = Car(color: "Red") // object of class Car
myCar.drive() // calling the object's method