override variables of upper classes
1,914
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
Comments
-
Little Monkey over 1 year
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 thatvar title
.I was trying with
@override void set
method, but I didn't understand how to use it properly. Can someone help me please? -
Little Monkey over 5 yearsActually, I want that this had to be done automatically, without instanciating the class and then setting the title. So, when I instanciate the sublcass object, it must already have the new title
-
Rémi Rousselet over 5 yearsThat's just a constructor. Nothing prevents you from adding a constructor to
Override
that sets a default title -
Little Monkey over 5 yearsUnderstood, I was getting a little bit confused by what I had to do. Thanks!