Super keyword in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Super keyword in dart is used to refer to the parent's class object's methods or variables. In simple terms, it is used to refer to the superclass properties and methods.

The most important use of the super keyword is to remove the ambiguity between superclass and subclass that have methods and variables with the same name.

The super keyword is able to invoke the parent's objects method and fields, as when we create an instance of the subclass in Dart, an instance of the parent class is also created implicitly.

Syntax

super.varName or super.methodName

As we can access both the variables and methods of the parent's class.

Accessing parent class variable

We can access the parent class variable which is also declared in the subclass.

Example

Consider the example shown below −

 Live Demo

class Animal {
   int count = 30;
}

class Dog extends Animal {
   int count = 70;
   void printNumber(){
      print(super.count);
   }
}

void main(){
   Dog obj= new Dog();
   obj.printNumber();
}

In the above example, we have two classes Animal and Dog, where Animal is the parent class (or Superclass) and the Dog is the child class (or subclass). It should be noted that the variable named count is declared in both the superclass and the subclass, and when we use super.count it will refer to the parent-class (superclass).

Output

30

Accessing parent class methods

We can also access the parent class methods that might also be declared in the subclass.

Example

Consider the example shown below −

 Live Demo

class Animal {
   void tellClassName(){
      print("Inside Animal Class");
   }
}

class Dog extends Animal {
   int count = 100;
   void tellClassName(){
      print("Inside Dog Class");
   }

   void printMessage(){
      tellClassName();
      super.tellClassName();
   }
}

void main(){
   Dog obj= new Dog();
   obj.printMessage();
}

Output

Inside Dog Class
Inside Animal Class
raja
Published on 24-May-2021 12:07:54
Advertisements