[英]Dart - Call Named Constructor using super vs class name
class Person {
late String name;
late int age;
Person();
Person.ap(this.name, this.age);
}
class Employee extends Person {
Employee(String name, int age) : super.ap(name, age); // This works
// This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
Employee(String name, int age) {
super.ap(name, age);
}
}
使用 super 或在括號內調用未命名的構造函數有什么區別?
您正在制作兩個同名的構造函數。 做這樣的事情
class Employee extends Person {
Employee(String name, int age) : super.ap(name, age);
Employee.foo(String name, int age): super.ap(name, age);
}
試試這個,只需在Person class
中創建一個名為ap
的 setter function
class Person {
late String name;
late int age;
Person();
Person.ap(this.name, this.age);
ap(String name, int age){ //add this
this.name=name;
this.age=age;
}
}
class Employee extends Person {
//here ap is name constructor
Employee(String name, int age) : super.ap(name, age);
//here ap is setter function in the person class
Employee.ap(String name, int age) {
super.ap(name, age);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.