简体   繁体   中英

Understanding Dart Default Constructors

I am coming from a Java background and trying to understand Dart. The Dart documentation states that:

If you don't declare a constructor, a default constructor is provided for you.

Consider the following then:

//Dart code; dart_app.dart
class Person{

   int age;
   String name;

   Person({@required this.name, this.age});

   Person.fromPerson(Person person){
     age = person.age;
     name = person.name;
   }
}

The person class has two constructors, so according to the docs, a default constructor will not be provided. Now I declare a subclass like so:

//Dart code; dart_app.dart
class Student extends Person{

  int rank;

  Student(this.rank);
}

I expect that instantiating Student , as defined, requires a call to the superclass (ie Person ) no-arg constructor. But since a no-arg constructor was not explicitly defined and since Dart (according to the docs) will not provide a default no-arg constructor (since other constructors have been explicitly defined) I expect a compile error. I get none. What am I missing?

The equivalent Java code below fails to compile as expected:

//Java code; File Person.java
package com.company;

public class Person {
    private int age;
    private String name;

    public Person(String name, int age) {
        this.age = age;
        this.name = name;
    }
}
//Java code; File Student.java
package com.company;

public class Student extends Person {
    int rank;
}

Student.java compile fails as expected: There is no default constructor available in 'com.company.Person' .

Thanks for your time.

All parameters of constructor Person are optional, which allows you to create instance of Student. In that case super constructor Person will be implicitly called with no parameters, thus allowing you to instantiate Student.

Please note that @required annotation is not language level, so does not make name strictly required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM