Super constructor in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

The subclass can inherit the superclass methods and variables, but it cannot inherit the superclass constructor. The superclass constructor can only be invoked with the use of the super() constructor.

The super() constructor allows a subclass constructor to explicitly call the no arguments and parametrized constructor of superclass.

Syntax

Subclassconstructor():super(){
}

Though, it is not even necessary to use the super() keyword as the compiler automatically or implicitly does the same for us.

When an object of a new class is created by making use of the new keyword, it invokes the subclass constructor which implicitly invokes the parent class's default constructor.

Let's make use of an example where we have a parent class (or superclass) and a children class, and both these classes have two constructors and when we create an object for the subclass, then implicitly the constructor inside the parentclass will also be invoked.

Example

Consider the example shown below −

 Live Demo

class SuperClass {
   SuperClass(){
      print("Constructor of Parent Class");
   }
}

class SubClass extends SuperClass {
   SubClass(){
      print("Constructor of Sub Class");
   }

   void display(){
      print("Inside Sub Class!!");
   }
}

void main(){
   SubClass obj= new SubClass();
   obj.display(); // invoking subclass method
}

Output

Constructor of Parent Class
Constructor of Sub Class
Inside Sub Class!!
raja
Published on 24-May-2021 12:05:15
Advertisements