Classes and Objects in Dart#
About#
In Dart, a class is a blueprint for creating objects (instances). It defines properties (fields) and behaviors (methods) that the objects created from the class can have. Objects are instances of classes, allowing you to reuse code, define reusable structures, and implement object-oriented principles.
- Class: A template or blueprint from which objects are created.
- Object: An instance of a class.
How to Define a Class#
To define a class in Dart, use the class
keyword followed by the class name. Inside the class, you define fields, constructors, and methods.
class Person {
// Fields (or properties)
String name;
int age;
// Constructor
Person(this.name, this.age);
// Method (behavior)
void greet() {
print('Hello, my name is $name and I am $age years old.');
}
}
How to Work with Classes and Objects#
Once you have defined a class, you can create objects (instances) of that class. You can assign values to fields and invoke methods.
Example#
void main() {
// Creating an instance of the Person class
Person person1 = Person('John', 30);
// Accessing the fields
print(person1.name); // Output: John
print(person1.age); // Output: 30
// Calling a method
person1.greet(); // Output: Hello, my name is John and I am 30 years old.
}
#Or
class Car {
// Fields
String model;
int year;
// Constructor
Car(this.model, this.year);
// Method
void showDetails() {
print('Car model: $model, Year: $year');
}
}
void main() {
// Creating objects (instances)
Car car1 = Car('Tesla', 2023);
Car car2 = Car('BMW', 2021);
// Accessing the fields
print(car1.model); // Output: Tesla
print(car2.year); // Output: 2021
// Calling methods
car1.showDetails(); // Output: Car model: Tesla, Year: 2023
car2.showDetails(); // Output: Car model: BMW, Year: 2021
}
In Dart, objects are created from classes, and they allow us to store and manipulate data using methods.