Understanding the building blocks of object-oriented programming with simple real-world examples.
A class is like a blueprint or template for creating objects. It defines properties (data) and behaviors (functions or methods) that the objects created from the class will have.
An object is an individual instance of a class. It has its own values for the properties defined in the class and can use the behaviors (methods) of the class.
Think of a class as a blueprint for making houses. The blueprint defines the size, number of rooms, color, and other details. But a blueprint alone is not a house. When a builder uses the blueprint and builds a house, that is an object. Each house built from the same blueprint can have different colors or furniture, but all follow the same plan.
class Car {
String color;
String model;
void drive() {
print("The $color $model is driving.");
}
}
void main() {
// Creating an object (instance) of Car
Car myCar = Car();
myCar.color = "red";
myCar.model = "Toyota";
myCar.drive(); // Output: The red Toyota is driving.
}
Here, Car is a class with properties color and model, and a method drive(). We create an object called myCar from the class and set its properties.
Classes and objects help organize code by bundling data and actions into logical units. This makes programs easier to understand, reuse, and maintain.
class Rectangle {
double width;
double height;
double area() {
return width * height;
}
}
void main() {
Rectangle rect = Rectangle();
rect.width = 5;
rect.height = 10;
print("Area: ${rect.area()}"); // Output: Area: 50
}
The Rectangle class has two properties and a method area() that calculates and returns the rectangle’s area.