class Point extends Test { num x; num y; num z; num get a { return this.x + this.y; } set a(num v) { x = v - y; } Point.fromJson(Map jsonMap) : this.x = jsonMap['x'], y = jsonMap['y'], super.fromJson({}) { print(this.x); print('In Point.fromJson(): ($x, $y, $z)'); } Point.aliasB(Map jsonMap, num z) : this.z = z, super.fromJson({}) { Point.fromJson(jsonMap); } Point(Map jsonMap, this.z) : super(jsonMap) { print('In Point(): ($x, $y, $z)'); x = jsonMap['x']; y = jsonMap['y']; print('In Point(): ($x, $y, $z)'); } } class Test { num x; num y; Test(Map map) : x = map['x'], y = map['y'] { print('In Parent.Test(): ($x, $y)'); } Test.fromJson(Map map) : this(map); } main(List<String> args) { new Point({'x': 1, 'y': 2}, 3); new Test({'x': 1, 'y': 2}); }
In Parent.Test(): (null, null) In Point(): (null, null, 3) In Point(): (1, 2, 3) In Parent.Test(): (1, 2)
希望有大佬能解答一下菜鸟的疑问
![]() | 1 IGJacklove 2020-01-12 18:24:25 +08:00 父类和子类都有相同名字的参数,Point 的 x 就是他自己的 x,如果想访问父类 Test 的 x,用 super.x |
![]() | 2 version0 OP @IGJacklove 额,你说的我知道啊,但是没解决我的问题啊,Test 类的构造方法没有给它的属性 x,y 赋值呢,是因为子类调用父类的构造方法时,不会执行父类构造方法 冒号后面的赋值语句吗?我把赋值语句放到{}里就能赋值 |
3 bytelee 2020-01-13 09:22:18 +08:00 这样看 Point 初始化的时候 父类的 Test 的初始化里边打印的应该是 point.x point.y 所以没有赋值。 |