What is "class" in Dart?

Fri, Dec 16, 2022

Read in 2 minutes

In this post we take a look at "class" keyword with some example codes.

In Dart, a class is a blueprint for creating objects. It defines the properties and methods that an object will have, and provides a way to organize and encapsulate related data and behavior.

Here’s an example of a simple class in Dart:

class Person {
  String name;
  int age;
  
  void sayHello() {
    print('Hello, my name is $name and I am $age years old.');
  }
}

In this example, we define a Person class with two properties (name and age) and one method (sayHello). The name property is a String that holds the person’s name, and the age property is an int that holds the person’s age. The sayHello method is a void function that prints a message to the console.

To create an instance of this class, we use the new keyword:

Person alice = new Person();
alice.name = 'Alice';
alice.age = 30;
alice.sayHello(); // prints "Hello, my name is Alice and I am 30 years old."

In this code, we create a new Person object called alice, and set the name and age properties to 'Alice' and 30, respectively. We then call the sayHello method on the alice object, which prints a message to the console.

Classes in Dart can also inherit from other classes using the extends keyword. This allows one class to inherit the properties and methods of another class, and then add or override behavior as needed. Here’s an example:

class Student extends Person {
  String major;
  
  void sayHello() {
    super.sayHello();
    print('I am studying $major.');
  }
}

Student bob = new Student();
bob.name = 'Bob';
bob.age = 20;
bob.major = 'Computer Science';
bob.sayHello(); // prints "Hello, my name is Bob and I am 20 years old. I am studying Computer Science."

In this code, we define a Student class that inherits from the Person class. The Student class has an additional major property, and overrides the sayHello method to print a more specific message. We create a new Student object called bob, set its properties, and call the sayHello method, which prints a message to the console that includes information from both the Person and Student classes.

In summary, a class in Dart is a blueprint for creating objects that encapsulate related data and behavior. Classes define properties and methods that objects will have, and can be used to organize and reuse code in a structured way. They can also be used to create inheritance hierarchies, allowing one class to inherit and extend the behavior of another class.


Shohruh AK



Category:

Dart

Tags:



See Also

What is "case" in Dart?
What is "break" in Dart?
What is "async" in Dart?
What is "assert" in Dart?
What is "as" in Dart language?