Sobes.tech
Junior

What aspects of object-oriented programming are present in the Dart language?

sobes.tech AI

Answer from AI

The following aspects of OOP are present in Dart:

  • Classes and objects: Ability to define classes with fields and methods, and create instances of classes (objects).
  • Encapsulation: Hiding implementation details through access modifiers (_ for private members) and getter/setter methods.
  • Inheritance: Extending the functionality of existing classes using the extends keyword.
  • Polymorphism: Ability to treat objects of different classes uniformly through a common interface or base class.
  • Abstraction: Creating abstract classes and interfaces to define contracts.

Example of a class in Dart:

class Animal {
  String _name; // Private field

  Animal(this._name); // Constructor

  String get name => _name; // Getter

  void makeSound() {
    print('Some generic animal sound'); // Method
  }
}

Example of inheritance:

class Dog extends Animal {
  Dog(String name) : super(name); // Call to the base class constructor

  @override // Override the base class method
  void makeSound() {
    print('Woof!');
  }
}

Example of polymorphism:

void makeAnimalSound(Animal animal) {
  animal.makeSound(); // Calls makeSound(), which can differ for different Animal types
}

// Usage:
// makeAnimalSound(Dog('Buddy')); // Will print "Woof!"

Dart also supports mixins using the with keyword, allowing code reuse across classes without direct inheritance.

What aspects of object-oriented programming are… - sobes.tech