Intro To Classes & Objects In Dart – Dart OOP Guide

Haris Bin Nasir Avatar

·

·

In Dart, classes and objects are fundamental concepts that drive object-oriented programming (OOP). A class acts as a blueprint or template that defines the properties and behaviors (methods) of an object, establishing a clear framework for development. An object represents a specific instance of a class and reflects the characteristics and functionalities outlined by that class. Using classes and objects helps you create code that remains structured, reusable, and maintainable. This approach promotes the development of scalable applications and encourages a modular design, making the codebase easier to manage and extend.

This post will cover the basics of defining classes and creating objects in Dart, along with constructors, methods, and properties.

For further information on detailed topics of Dart, click here.

1. Defining a Class

A class in Dart is defined using the class keyword, followed by the class name. Inside the class, you can define properties (variables) and methods (functions) that describe the behavior of the class.

Example: Basic Class Definition
class Car {
  String brand = 'Toyota';
  String model = 'Corolla';
  int year = 2020;

  void drive() {
    print('The $brand $model is driving.');
  }
}

In this example, the Car class has three properties: brand, model, and year, as well as a method called drive that prints a message when called.

2. Creating an Object

Once you have defined a class, you can create an object (an instance of that class) by using the new keyword or by directly calling the class name.

Example: Creating an Object
void main() {
  Car myCar = Car();  // Create an object of the Car class
  print('Brand: ${myCar.brand}');
  myCar.drive();  // Output: The Toyota Corolla is driving.
}

In this example, an object myCar is created from the Car class, and the properties and methods of the object are accessed.

3. Constructors

A constructor is a special method that is called when an object is created. It initializes the properties of the object. Dart provides a default constructor if you don’t define one, but you can also create custom constructors.

Example: Basic Constructor
class Car {
  String brand;
  String model;
  int year;

  // Constructor
  Car(String b, String m, int y) {
    brand = b;
    model = m;
    year = y;
  }

  void drive() {
    print('The $brand $model is driving.');
  }
}

void main() {
  Car myCar = Car('Honda', 'Civic', 2022);
  print('Brand: ${myCar.brand}');
  myCar.drive();  // Output: The Honda Civic is driving.
}

In this example, the constructor initializes the properties brand, model, and year when the object is created.

4. Named Constructors

Dart also supports named constructors, which allow you to create multiple constructors within a single class. This is useful when you need different ways to initialize objects.

Example: Named Constructor
class Car {
  String brand;
  String model;
  int year;

  // Named constructor for electric cars
  Car.electric() {
    brand = 'Tesla';
    model = 'Model S';
    year = 2022;
  }

  void drive() {
    print('The $brand $model is driving.');
  }
}

void main() {
  Car myElectricCar = Car.electric();
  print('Brand: ${myElectricCar.brand}');
  myElectricCar.drive();  // Output: The Tesla Model S is driving.
}

In this example, the Car.electric named constructor initializes a specific type of car, a Tesla Model S.

5. Getters and Setters

Getters and setters are special methods that provide controlled access to the properties of a class. A getter retrieves the property value, while a setter updates it. These methods help encapsulate the data and ensure that the class’s internal state remains consistent.

Example: Getters and Setters
class Car {
  String _brand;  // Private property

  // Constructor
  Car(this._brand);

  // Getter
  String get brand => _brand;

  // Setter
  set brand(String b) {
    _brand = b;
  }

  void drive() {
    print('The $_brand is driving.');
  }
}

void main() {
  Car myCar = Car('Ford');
  print('Brand: ${myCar.brand}');  // Output: Brand: Ford
  myCar.brand = 'BMW';  // Update the brand using setter
  print('Updated Brand: ${myCar.brand}');  // Output: Updated Brand: BMW
  myCar.drive();  // Output: The BMW is driving.
}

In this example, the _brand property is private, and access to it is controlled through the getter and setter methods.

6. Inheritance

Inheritance is a key concept in object-oriented programming that allows a class to inherit properties and methods from another class. The class that inherits is called a subclass, and the class from which it inherits is called a superclass.

Example: Inheritance
class Vehicle {
  String brand = 'Generic';

  void start() {
    print('The vehicle is starting.');
  }
}

class Car extends Vehicle {
  String model = 'Sedan';

  void drive() {
    print('The $brand $model is driving.');
  }
}

void main() {
  Car myCar = Car();
  myCar.start();  // Output: The vehicle is starting.
  myCar.drive();  // Output: The Generic Sedan is driving.
}

In this example, the Car class inherits the brand property and start method from the Vehicle class, while adding its own model property and drive method.

7. Method Overriding

Method overriding allows a subclass to implement a method differently from how its superclass defines it. This approach helps modify or extend the behavior of the inherited method.

Example: Method Overriding
class Vehicle {
  void start() {
    print('The vehicle is starting.');
  }
}

class Car extends Vehicle {
  @override
  void start() {
    print('The car is starting.');
  }
}

void main() {
  Car myCar = Car();
  myCar.start();  // Output: The car is starting.
}

In this example, the start method in the Car class overrides the start method in the Vehicle class.

8. Static Members

Static members belong to the class rather than any instance of the class. This means you can access static properties and methods without creating an object of the class.

Example: Static Members
class Car {
  static int numberOfCars = 0;

  String brand;

  Car(this.brand) {
    numberOfCars++;
  }

  static void showTotalCars() {
    print('Total cars: $numberOfCars');
  }
}

void main() {
  Car car1 = Car('Toyota');
  Car car2 = Car('Honda');

  Car.showTotalCars();  // Output: Total cars: 2
}

In this example, the static member numberOfCars keeps track of the total number of cars created, and the static method showTotalCars displays this count.

Conclusion

Dart classes and objects form the foundation of object-oriented programming in Dart. By understanding how to define classes, create objects, and utilize features like constructors, inheritance, and static members, you can write more organized and maintainable code. Whether you’re building simple applications or complex systems, mastering Dart’s class and object concepts will significantly enhance your programming skills.

Happy Coding…!!!

Leave a Reply

Your email address will not be published. Required fields are marked *