Class and Object Oriented Programming with Dart


Class and Object Oriented Programming with Dart

The Dart programming language stands out with its powerful object-oriented programming (OOP) features in modern application development processes. Especially when developing mobile and web applications with Flutter, it is very important to use Dart's class and OOP features effectively in order to make the code modular, readable, and maintainable. In this article, we will examine in detail the concepts of "Class and object-oriented programming with Dart".

Defining and Using Classes in Dart

In Dart, a class defines the structure and behaviors of an object. Thanks to classes, repetitive code is avoided, code can be reused, and projects become more manageable.

A Simple Class Definition


class Car {
  String brand;
  int year;
  
  Car(this.brand, this.year);

  void printInfo() {
    print('Brand: ' + brand + ', Year: ' + year.toString());
  }
}

void main() {
  Car car1 = Car('Toyota', 2022);
  car1.printInfo();
}

In the example above, we defined a class called Car. We assigned values to the class properties via the constructor and printed out the information through a function.

How are OOP Principles Applied with Dart?

The basic principles of object-oriented programming with Dart are applied as follows:

1. Encapsulation

This is the consolidation of data and functions within a single structure (class). The _propertyName is used for private properties.


class Person {
  String _name; // private, inaccessible from outside
  Person(this._name);
  String get name => _name;
}

2. Inheritance

This is when a class inherits properties and methods from another class.


class Animal {
  void makeSound() {
    print('A sound...');
  }
}

class Cat extends Animal {
  @override
  void makeSound() {
    print('Meow!');
  }
}

3. Polymorphism

This is when the same method runs differently in different classes.


void soundTest(Animal animal) {
  animal.makeSound();
}

void main() {
  Cat cat = Cat();
  soundTest(cat); // The makeSound method of Cat is called
}

Conclusion: Modern Development with Dart Classes and OOP

"Class and object-oriented programming with Dart" is an indispensable approach that increases software quality in modern mobile and web projects. When you use class structures and OOP principles correctly, your projects become both readable and maintainable. Especially in Flutter projects, be sure to take advantage of Dart's rich object-oriented features to design your code in a scalable and modular way.