Super Keyword

  1. Definition
  2. The concept of super keyword comes with the idea of inheritance in Dart. Suppose you have a member variable or method of the same name in the derived class as you do in the base class.

    When referring to that variable/method, how would the program know which one are you referring to: the base class or the derived class?

    This is where super comes into play. The super keyword in Dart acts like a reference variable to the parent class.

    It’s mainly used when we want to access a variable, method, or constructor in the base class, from the derived class.


  3. Accessing base class variables
  4. When we have the data members of the same name in both the base and derived class, we can use the super keyword to access the base class member in the derived class.

    Example:


    class Base {

      int nb = 25;

    }

     

    class Derived extends Base {

      int nb = 50;

      void printNb() {

        print("Base nb : ${super.nb}");

        print("Derived nb : $nb");

      }

      void setSuperNb(int x) {

        super.nb = x;

      }

    }

     

    void main() {

      var object = Derived();

      object.printNb();

      object.nb = 60;

      object.printNb();

      object.setSuperNb(11);

      object.printNb();

    }



    Base nb : 25
    Derived nb : 50

    Base nb : 25
    Derived nb : 60

    Base nb : 11
    Derived nb : 60

  5. Invoking base class method
  6. When the name of a function is the same in both the base and derived class, the super keyword can be used to invoke the base class function in the derived class.

    Example:

    class Base {

      void speak() {

        print("Hi! I am from the base Class");

      }

    }

     

    class Derived extends Base {

      void speak() {

        print("Hello! I am from the derived Class");

      }

      void listen() {

        super.speak();

        speak();

      }

    }

     

    void main() {

      var object = Derived();

      object.listen();

    }



    Hi! I am from the base Class
    Hello! I am from the derived Class

  7. Invoking base class constructor
  8. The super keyword can also be used to invoke the parent class constructor, both parameterized and empty, in the derived class.

    Example:

    class Base {

      Base() {

        print("Base Constructor");

      }

    }

     

    class Derived extends Base {

      Derived() : super() {

        print("Derived Constructor");

      }

    }

     

    void main() {

      var object = Derived();

    }



    Base Constructor
    Derived Constructor