override variables of upper classes

孤街浪徒 提交于 2019-12-25 02:28:49

问题


I have an upper class that has a var title and then I have different classes, that extend this upper one, in which I want to override that var title.

I was trying with @override void set method, but I didn't understand how to use it properly. Can someone help me please?


回答1:


You can use getter and setter combined with super to achieve the desired result:

class Foo {
  String title;
}

class Override extends Foo {
  String get title {
    print("get title");
    return super.title;
  }

  set title(value) {
    print("Set title");
    super.title = value;
  }
}

Foo f = Override();
f.title = "Hello World";
print(f.title);

This will print

Set title
get title
Hello World


来源:https://stackoverflow.com/questions/52151651/override-variables-of-upper-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!