In this chapter, we will learn about the dart objects and how they are used with the help of examples.
Dart Object
In the previous chapter, we learned about the dart classes. A class is a blueprint for an object. A class consists of data for the object. We can create an object from a class.
For example,
class Car {
// field
String color = "black";
// function
void screen() {
print(color);
}
}
In the above example, Car is the class.
Now we can create multiple objects from the above class.
Create an Object
To create dart object from the class, we use the new keyword followed by the class name.
The syntax for creating an object is:
var object_name = new class_name();
The object_name refers to the name of the object.
The new keyword instantiates the class.
For example,
var obj1 = new Car("Model");
Example of an Object
class Car {
String name = 'car_name';
String color = 'car_color';
void screen() {
print(color + ' ' + name);
}
}
void main() {
var tesla = new Car();
tesla.name = 'Tesla';
tesla.color = 'Red';
print(tesla);
print(tesla.name);
print(tesla.color);
tesla.screen();
}
Output
Instance of 'Car'
Tesla
Red
Red Tesla
In the above example, Car is a class and tesla is an object.
We can access the fields and methods of a class using the dot notation.