override variables of upper classes

2019-08-23 02:57发布

问题:

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