Dart – Class

In object-oriented programming, a class is a blueprint for creating objects. A class defines the properties and methods that an object will have.

Declaring Class In Dart

You can declare a class in dart using the class keyword followed by class name and braces {}. It’s a good habit to write class name in PascalCase

Syntax:

class ClassName {
// properties or fields
// methods or functions
}
  • The class keyword is used for defining the class.
  • ClassName is the name of the class and must start with capital letter.
  • Body of the class consists of properties and functions.
  • Properties are used to store the data. It is also known as fields or attributes.
  • Functions are used to perform the operations. It is also known as methods.

Example :

class Person {
  String? name;
  String? phone;
  bool? isMarried;
  int? age;

  void displayInfo() {
    print("Person name: $name.");
    print("Phone number: $phone.");
    print("Married: $isMarried.");
    print("Age: $age.");
  }
}

In this example above, there is class Person with four properties: namephoneisMarried, and age. The class also has a method called displayInfo, which prints out the values of the four properties.

Leave a comment

Your email address will not be published. Required fields are marked *