A class in Dart is a blueprint for creating objects, providing a blueprint for the data and behavior that objects of the class should have. In other words, classes define the structure of objects, and objects are instances of classes.
Here’s an example of a simple class in Dart:
class Dog {
String name;
int age;
void bark() {
print("Bark!");
}
}
In this example, we’ve defined a class named Dog
with two instance variables name
and age
, and a method bark
that prints “Bark!” to the console.
To create an object of a class, you use the new
keyword followed by the class name:
Dog dog = new Dog();
In this example, a new Dog
object is created and stored in the variable dog
.
You can access the instance variables and methods of an object by using the dot notation. For example:
dog.name = "Fido";
dog.age = 3;
dog.bark(); // Output: Bark!
In this example, the instance variables name
and age
of the dog
object are assigned values, and the bark
method is called.
Dart classes also support constructors, which are special methods that are called when an object is created. Constructors are used to initialize an object’s instance variables. Here’s an example of a class with a constructor:
class Dog {
String name;
int age;
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void bark() {
print("Bark!");
}
}
In this example, we’ve added a constructor to the Dog
class that takes two parameters name
and age
. The constructor initializes the instance variables name
and age
with the values passed as arguments.
To create an object using a constructor, you simply pass the required arguments when calling the new
keyword:
Dog dog = new Dog("Fido", 3);
dog.bark(); // Output: Bark!
In this example, a Dog
object is created using the constructor and assigned to the variable dog
. The bark
method is then called on the dog
object.
In conclusion, classes in Dart provide a way to define the structure of objects, including the instance variables and methods that objects should have. By creating objects from classes, you can easily create and manipulate objects that have the same structure and behavior, making it easy to build complex, scalable applications.
Average Rating