Start Coding

Topics

Dart Classes: Building Blocks of Object-Oriented Programming

Classes are fundamental to object-oriented programming in Dart. They serve as blueprints for creating objects, encapsulating data and behavior into reusable units.

Defining a Class

In Dart, you can define a class using the class keyword. Here's a simple example:


class Person {
  String name;
  int age;

  void sayHello() {
    print('Hello, my name is $name');
  }
}
    

This class, Person, has two properties (name and age) and a method (sayHello).

Creating Objects

To create an object from a class, use the new keyword (optional in Dart 2.0+) followed by the class name:


var person = Person();
person.name = 'Alice';
person.age = 30;
person.sayHello(); // Outputs: Hello, my name is Alice
    

Constructors

Constructors initialize object properties when an instance is created. Dart provides several ways to define constructors:

Default Constructor


class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

var person = Person('Bob', 25);
    

Named Constructors

Dart allows multiple constructors through named constructors:


class Person {
  String name;
  int age;

  Person(this.name, this.age);

  Person.guest() {
    name = 'Guest';
    age = 18;
  }
}

var guest = Person.guest();
    

Instance Variables and Methods

Instance variables store object-specific data, while methods define object behavior. Both are accessed using dot notation:


class Car {
  String model;
  int year;

  Car(this.model, this.year);

  void displayInfo() {
    print('$model ($year)');
  }
}

var myCar = Car('Tesla Model 3', 2022);
myCar.displayInfo(); // Outputs: Tesla Model 3 (2022)
    

Inheritance

Dart supports single inheritance, allowing classes to inherit properties and methods from a parent class:


class Vehicle {
  void move() {
    print('Moving...');
  }
}

class Car extends Vehicle {
  void honk() {
    print('Honk!');
  }
}

var car = Car();
car.move(); // Inherited from Vehicle
car.honk(); // Defined in Car
    

Best Practices

  • Use meaningful names for classes, following PascalCase convention.
  • Keep classes focused on a single responsibility.
  • Utilize Dart Getters and Setters for controlled access to properties.
  • Consider using Dart Abstract Classes for defining interfaces.
  • Implement Dart Interfaces to define a contract for classes.

Advanced Concepts

As you progress, explore these advanced class-related concepts in Dart:

Classes form the backbone of object-oriented programming in Dart. They provide a powerful way to structure your code, promote reusability, and model real-world entities in your applications.