Classes are fundamental to object-oriented programming in Dart. They serve as blueprints for creating objects, encapsulating data and behavior into reusable units.
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
).
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 initialize object properties when an instance is created. Dart provides several ways to define constructors:
class Person {
String name;
int age;
Person(this.name, this.age);
}
var person = Person('Bob', 25);
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 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)
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
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.