Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call on the super class' constructor and other statements in Dart?

Given this code:

abstract class Animal {

        String name;

        Animal (String this.name) {
        }

}

class Dog extends Animal {

        // Why does this fail
        Dog() {
            super("Spot");
            print("Dog was created");
        }

        // Compared to this
        // Dog() : super("Spot");

}

According to multiple docs:

  • https://www.dartlang.org/dart-tips/dart-tips-ep-11.html
  • https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-implicit-interfaces

You can call the super class' constructor with the following syntax:

Dog() : super("Spot");

I assume this is some kind of a shortcut syntax to quickly call the super class' constructor. But what if I also want to do additional things in the Dog's constructor, such as calling print.

Why doesn't this work, and what is the proper way to write the code?

// Why does this fail
Dog() {
    super("Spot");
    print("Dog was created");
}
like image 320
corgrath Avatar asked Jan 09 '14 23:01

corgrath


People also ask

How do you call a constructor in darts?

In dart, the subclass can inherit all the variables and methods of the parent class, with the use of extends keyword but it can't inherit constructor of the parent class. To do so we make use of super constructor in the dart. There are two ways to call super constructor: Implicitly.

How do you access the super class variable in darts?

Syntax: // To access parent class variables super. variable_name; // To access parent class method super. method_name();

How are this () and super () Used with constructor?

super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.


2 Answers

You can call super in this way:

abstract class Animal {
  String name;
  Animal (String this.name);
}

class Dog extends Animal {
  Dog() : super('Spot') {
    print("Dog was created");
  }
}

void main() {
  var d = new Dog(); // Prints 'Dog was created'.
  print(d.name);     // Prints 'Spot'.
}
like image 195
Shailen Tuli Avatar answered Sep 20 '22 18:09

Shailen Tuli


If you want execute code before the super you can do it like that:

abstract class Animal {
  String name;
  Animal (this.name);
}

class Cat extends Animal {
  String breed;

  Cat(int i):
    breed = breedFromCode(i),
    super(randomName());

  static String breedFromCode(int i) {
    // ...
  }

  static String randomName() {
    // ...
  }
}
like image 41
Ernesto Elsäßer Avatar answered Sep 18 '22 18:09

Ernesto Elsäßer