结论:
示例1:
class Mark{
String name = "James with mark";
void introduceSelf() {
print(name);
}
}
class Person with Mark {
}
void main() {
Person().introduceSelf();
print(Person().name);
}
输出:
James with mark
James with mark
从输出结果可以看出 Persion获得Mark的成员变量和方法
示例2:
class Mark{
String name = "James with mark";
void introduceSelf() {
print(name);
}
}
class Person with Mark {
String name = "James";
int age = 18;
void introduceSelf() {
print(name);
print('I am $age years old');
}
}
void main() {
Person().introduceSelf();
}
输出
James
I am 18 years old
从输出结果可以看出,with 并没有覆盖掉Persion类的成员变量和方法,也就是说不会影响原有类的成员变量和方法。
示例3:
class Mark{
String name = "James with mark";
void introduceSelf() {
print(name);
}
}
class Person with Mark {
String name = "James";
int age = 18;
// void introduceSelf() {
// print(name);
// print('I am $age years old');
// }
}
void main() {
Person().introduceSelf();
}
输出
James
从输出结果可以看出,Persion通过with 获得了 Mark的 introduceSelf() 方法,并且成员变量name没有被覆盖。等同于如下:
class Person with Mark {
String name = "James";
int age = 18;
void introduceSelf() {
print(name);
}
}
示例4:
class Mark{
String name = "James with mark";
void introduceSelf() {
print(name);
}
}
class MarkB{
String name = "James with markb";
void introduceSelf() {
print(name);
}
}
class Person with Mark ,MarkB{
}
class PersonB with MarkB,Mark{
}
void main() {
Person().introduceSelf();
print(Person().name);
PersonB().introduceSelf();
print(PersonB().name);
}
输出结果:
James with markb
James with markb
James with mark
James with mark
从输出结果可以看出,with 有先后顺序,后with的类会覆盖之前的。