free geoip
38

Dart Inheritance and Constructors Tutorial Guide

Understanding inheritance and constructors in Dart is crucial for writing clean, maintainable, and reusable code. In object-oriented programming, inheritance allows…

Understanding inheritance and constructors in Dart is crucial for writing clean, maintainable, and reusable code. In object-oriented programming, inheritance allows one class to acquire properties and methods from another, while constructors are special functions used to create instances of classes.

Dart inheritance and constructors

This tutorial will guide you through the concepts of inheritance and constructors in Dart with simple, beginner-friendly examples.

Why Use Inheritance?

Inheritance promotes code reuse and modular design. It helps create a hierarchy between classes, such as parent and child relationships. Dart supports single inheritance, which means a class can inherit from only one superclass.

Understanding Constructors

Constructors in Dart are used to initialize class objects. Dart provides default constructors, named constructors, and allows constructor chaining via super() for inheritance.

Example Code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Parent Class
class Animal {
String name;
// Constructor
Animal(this.name);
void sound() {
print('$name makes a sound');
}
}
// Child Class inheriting Animal
class Dog extends Animal {
String breed;
// Constructor with super()
Dog(String name, this.breed) : super(name);
@override
void sound() {
print('$name barks');
}
}
void main() {
Dog myDog = Dog('Buddy', 'Golden Retriever');
myDog.sound(); // Output: Buddy barks
}
// Parent Class class Animal { String name; // Constructor Animal(this.name); void sound() { print('$name makes a sound'); } } // Child Class inheriting Animal class Dog extends Animal { String breed; // Constructor with super() Dog(String name, this.breed) : super(name); @override void sound() { print('$name barks'); } } void main() { Dog myDog = Dog('Buddy', 'Golden Retriever'); myDog.sound(); // Output: Buddy barks }
// Parent Class
class Animal {
  String name;

  // Constructor
  Animal(this.name);

  void sound() {
    print('$name makes a sound');
  }
}

// Child Class inheriting Animal
class Dog extends Animal {
  String breed;

  // Constructor with super()
  Dog(String name, this.breed) : super(name);

  @override
  void sound() {
    print('$name barks');
  }
}

void main() {
  Dog myDog = Dog('Buddy', 'Golden Retriever');
  myDog.sound(); // Output: Buddy barks
}

This example shows how the Dog class inherits from Animal, overrides the sound() method, and calls the superclass constructor using super(name).

For a deeper dive into Dart OOP principles, visit the official Dart documentation.

rysasahrial

Leave a Reply

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