Classes In Dart Programming (PART 1)

Classes In Dart Programming (PART 1)

In Dart, a class is a blueprint for creating objects. It defines the properties and behaviors that an object of that class will have. A class is a way of organizing and structuring code in an object-oriented manner.

To create a class in Dart, you use the class keyword followed by the name of the class. For example, you could create a Dog class like this:

class Dog {
  // properties and methods go here
}

properties and methods

A class typically has two main parts: properties and methods. Properties are the characteristics or attributes of an object, such as its name, age, or colour. Methods are the actions or behaviors that an object can perform, such as barking, wagging its tail, or chasing a ball.

Here is an example of a Dog class that has some properties and methods:

class Dog {
  // This is the name property
  String name;

  // This is the age property
  int age;

  // This is the bark method
  void bark() {
    print('Woof! Woof!');
  }

  // This is the wagTail method
  void wagTail() {
    print('*wags tail*');
  }

  // This is the chaseBall method
  void chaseBall() {
    print('*chases ball*');
  }
}

Objects

Once you have defined a class, you can use it to create objects. To create an object from a class, you use the new keyword followed by the name of the class and some arguments for the constructor. The constructor is a special method that is called when an object is created, and it is used to initialize the properties of the object.

Here is an example of how you might create an object from the Dog class:

// Create a new Dog object
Dog dog = new Dog(name: 'Fido', age: 3);

// Print the name and age of the dog
print(dog.name); // Output: Fido
print(dog.age); // Output: 3

// Call the bark method of the dog
dog.bark(); // Output: Woof! Woof!

In this example, we create a new Dog object with the name of "Fido" and an age of 3. We then print the name and age of the dog and call the bark method of the dog to make it bark.

Classes in Dart are a powerful tool for organizing and structuring code. They allow you to create objects that have specific properties and behaviors, and to reuse that code in different parts of your application. This can make your code more efficient, modular, and easy to maintain.

I hope you found this article easy to understand. Thank you for Reading.