Dart class inheritance : extends and override

Class inheritance :

Class inheritance allows one class to inherit properties of a different class. Dart supports single inheritance i.e. one class can inherit from only one class. extends keyword is used for inheritance. The syntax of extends is :

ClassA extends ClassB{}

i.e. ClassA is extending ClassB or ClassA inherits ClassB. By default, all classes in dart extends Object class. Also, ClassB is called parent class or base class or super class and ClassA is called child class or sub class.

In this post, I will quickly show you how inheritance works in dart with examples.

Class inheritance example :

For the below example :

class Vehicle {
  String type = 'Vehicle';

  String printDetails() => 'Type : $type';
}

class Car extends Vehicle {}

void main() {
  var car = Car();
  print(car.printDetails());
}

Explanation :

Here, Car is extending Vehicle. Vehicle is the super class and Car is sub class. We haven’t defined anything in Car but it inherits the variable type and method printDetails from its parent class automatically.

Inside the main method, we are creating one Car object and calling the printDetails method on this object. This method is a parent class method.

Executing the above program will print the below output :

Type : Vehicle

What will be the output if we redefine the type variable in the child class ?

class Vehicle {
  String type = 'Vehicle';

  String printDetails() => 'Type : $type';
}

class Car extends Vehicle {
  String type = 'Car';
}

void main() {
  var car = Car();
  print(car.printDetails());
}

It will use the variable defined inside the child class. Output :

Type : Car

Overriding class members :

We can override instance methods, getters and setters of a super class. override annotation is used to define that we are overriding a member. The child class method is called overriding method and the parent class method is called overridden method.

Example of method overriding :

class Vehicle {
  String type = 'Vehicle';

  String printDetails() => 'Type : $type';
}

class Car extends Vehicle {
  
  String printDetails() => 'Type of vehicle : Car';
}

void main() {
  var car = Car();
  print(car.printDetails());
}

Here, we are overriding printDetails method in the child class Car. It will print the below output :

Type of vehicle : Car

Dart extend override example

i.e. it executes the overriding method.

The main advantage is that we can override methods in all subclasses separately. Without changing the parent class code, we can have separate implementations.

Similar tutorials :