Dart Classes and Objects

Understanding the building blocks of object-oriented programming with simple real-world examples.

1. What is a Class? (Programming Definition)

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.

2. What is an Object? (Programming Definition)

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.

3. Real-World Example: Class and Object

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.

4. Dart Code Example of Class and Object

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.

5. Why Use Classes and Objects?

Classes and objects help organize code by bundling data and actions into logical units. This makes programs easier to understand, reuse, and maintain.

6. Another Example: Class with Method Returning a Value

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.