Mastering Dart: A Comprehensive Guide to Classes

Mastering Dart: A Comprehensive Guide to Classes

What are Classes?

In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from other bicycles.

When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics by building many bicycles from the same blueprint--it would be very inefficient to produce a new blueprint for every individual bicycle they manufactured.

In object-oriented software, it's also possible to have many objects of the same kind that share characteristics. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. Software "blueprints" for objects are called classes.

Definition: A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind.

Why Classes?

Let's consider a program for a car factory. Without utilizing classes, representing 100 cars with 50 components each would entail managing 5000 variables, leading to complexity and error-prone referencing.

However, with classes, we can model each car as an object, reducing the code to just 100 objects organized hierarchically. This approach fosters code reusability, scalability, and maintainability, thanks to encapsulation, inheritance, and polymorphism.

Using classes also creates a conceptual model close to the real world, reducing the gap between desired and delivered functionality. In summary, leveraging classes enhances code organization, promotes reuse, and aligns with real-world concepts, resulting in robust and maintainable software solutions.

Actually, you don’t need classes. Classes are one way of describing characteristics of an object. Every object that belongs to a given class has the same characteristics.

How to use classes?

Declaring class in Dart

Syntax:

class class_name {
   // Body of class
}

In the above syntax:

  • Class is the keyword use to initialize the class.

  • class_name is the name of the class.

  • Body of class consists of fields, constructors, getter and setter methods, etc.

Declaring objects in Dart

Syntax:

var object_name = ClassName(arguments);

In the above syntax:

  • object_name is the name of the object and its naming is similar to the variable name in dart.

  • class_name is the name of the class whose instance variable is been created.

  • arguments are the input which are needed to be pass if we are willing to call a constructor.

After the object is created, there will be the need to access the fields which we will create. We use the dot(.) operator for that purpose.

Syntax:

 // For accessing the property
object_name.property_name;

// For accessing the method
object_name.method_name();

To demonstrate, let's create a Bicycle class. This class will have instance variables like the current gear and pedaling speed (cadence), just like real bicycles. We'll also include methods to change gears, brake, and adjust pedaling speed.

After defining the Bicycle class, we'll create an actual bicycle by instantiating the class. This means we'll create an object of type Bicycle. Each bicycle we create will have its own gear and pedaling speed.

// Define the Bicycle class
class Bicycle {
  // Instance variables
  int currentGear = 1;
  int currentCadence = 0;

  // Method to change gears
  void changeGear(int newGear) {
    currentGear = newGear;
    print('Changed gear to $newGear');
  }

  // Method to brake
  void brake() {
    print('Braking...');
  }

  // Method to change pedaling speed
  void changeCadence(int newCadence) {
    currentCadence = newCadence;
    print('Changed pedaling speed to $newCadence');
  }
}

void main() {
  // Instantiate the Bicycle class
  var myBike = Bicycle();

  // Change gear to 3
  myBike.changeGear(3);

  // Change pedaling speed to 50
  myBike.changeCadence(50);

  // Brake
  myBike.brake();
}

One challenge arises when we need to initialize different instances of a class with varying values, such as setting currentGear to 3 for one instance and 2 for another. To address this challenge, the concept of constructors was introduced.

Constructors

Constructors are special methods in object-oriented programming languages, such as Dart, used for initializing objects when they are created. They define how an object should be set up and initialized with initial values. Constructors are automatically called when an object is instantiated, ensuring that the object is properly initialized before it is used.

Syntax: For a default constructor

class MyClass {
  // Default constructor
  MyClass() {
    // Constructor body
  }
}

Syntax: For a parameterized constructor

class MyClass {
  // Parameterized constructor
  MyClass(int param1, String param2) {
    // Constructor body
  }
}

Syntax: For a named constructor

class MyClass {
  // Parameterized constructor
  MyClass.name1(int param1, String param2) {
    // Constructor body
  }
    MyClass.name2() {
    // Constructor body
  }
.
.
.
}

Let's examine how our code will appear when employing a constructor.

// Define the Bicycle class with a constructor
class Bicycle {
  // Instance variables
  int currentGear;
  int currentCadence;

  // Constructor
  Bicycle(int gear, int cadence) {
    currentGear = gear;
    currentCadence = cadence;
  }

  // Method to change gears
  void changeGear(int newGear) {
    currentGear = newGear;
    print('Changed gear to $newGear');
  }

  // Method to brake
  void brake() {
    print('Braking...');
  }

  // Method to change pedaling speed
  void changeCadence(int newCadence) {
    currentCadence = newCadence;
    print('Changed pedaling speed to $newCadence');
  }
}

void main() {
  // Create a Bicycle object with initial gear 1 and cadence 0
  var myBike = Bicycle(1, 0);

  // Change gear to 3
  myBike.changeGear(3);

  // Change pedaling speed to 50
  myBike.changeCadence(50);

  // Brake
  myBike.brake();
}

Conclusion

Classes serve as blueprints for creating objects, allowing developers to encapsulate data and behavior into cohesive units. Through inheritance, classes can share and extend functionality, promoting code reuse and modularity. Polymorphism enables flexible and extensible code, where objects of different types can be treated uniformly.

In summary, mastering object-oriented programming in Dart is a journey worth undertaking for any developer aspiring to build high-quality, professional-grade applications. With a solid understanding of OOP principles and Dart's powerful features, developers can unlock endless possibilities for innovation and creativity in their software projects.