[英]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);
}
}
What's the difference of calling unnamed constructor using super or inside the parenthesis?使用 super 或在括号内调用未命名的构造函数有什么区别?
You are making two same-named constructors.您正在制作两个同名的构造函数。 Do something like this做这样的事情
class Employee extends Person {
Employee(String name, int age) : super.ap(name, age);
Employee.foo(String name, int age): super.ap(name, age);
}
try this, just create a setter function named ap
in the Person class
试试这个,只需在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.