Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

providing default implementation for method in abstract class

Tags:

dart

In the example below I was hoping sum getter would return 8, but it is a compile error.

Class 'B' has no instance getter 'sum'.

According to the spec:

Using an abstract class instead of an interface has important advantages. An abstract class can provide default implementations; it can also provide static methods, obviating the need for service classes such as Collections or Lists, whose entire purpose is to group utilities related to a given type.

What is the correct way to provide a default implementation of sum that adds x and y?

abstract class A {
  int get x;
  int get y;
  int get sum => x+y;
}

class B implements A {
  int get x => 3;
  int get y => 5;
}

main() {
  B b = new B();
  print(b.x);
  print(b.sum); // Not working, why not 8?
}
like image 679
user1338952 Avatar asked Jul 22 '13 13:07

user1338952


1 Answers

You have to make B extend A instead of implement.

abstract class A {
  int get x;
  int get y;
  int get sum => x+y;
}

class B extends A {
  int get x => 3;
  int get y => 5;
}

main() {
  B b = new B();
  print(b.x);
  print(b.sum); // displays 8
}

Alternatively if you don't want to use extends because your class may already extend an other class, you can use mixins :

abstract class M {
  int get x;
  int get y;
  int get sum => x+y;
}

class A {
  String s = "s";
}
class B extends A with M {
  int get x => 3;
  int get y => 5;
}

main() {
  B b = new B();
  print(b.s);
  print(b.x);
  print(b.sum); // displays 8
}
like image 120
Alexandre Ardhuin Avatar answered Sep 28 '22 02:09

Alexandre Ardhuin