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
Share:
1,914
Little Monkey
Author by

Little Monkey

I'm just a little monkey!

Updated on December 06, 2022

Comments

  • Little Monkey
    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 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?

  • Little Monkey
    Little Monkey over 5 years
    Actually, 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
    Rémi Rousselet over 5 years
    That's just a constructor. Nothing prevents you from adding a constructor to Override that sets a default title
  • Little Monkey
    Little Monkey over 5 years
    Understood, I was getting a little bit confused by what I had to do. Thanks!