简体   繁体   中英

Abstract methods in Dart

I'm implementing an inheritance hierarchy in which derived-class construction consists only of a call to the base-class constructor. The base-class constructor then calls method(s) implemented only in the derived-class.

I have a basic implementation, but DartEditor of course complains about the missing methods in the base class. How can I make it happy?

Edit: I hadn't yet ran any code before posting my question, and it turns out that method binding works in the manner one would expect:

void main() {
    new B();
}

abstract class A {
    A() {
        x();
        y();
    }
    x() => print('A.x');
    y() => print('A.y');
}

class B extends A {
    B() : super();

    @override
    x() => print('B.x');
}

The above code outputs the following, which is the desired behavior. B 's constructor calls A 's constructor which calls x() . But since there is an x() defined for B , this is the one called:

B.x
A.y

It interesting to note that, although x() is being called by A 's constructor, Dart somehow knows to call B 's x() . I presume this is because the call chain looks roughly like the following:

B() -> A() -> B::x()

At runtime, Dart inspects the call chain to determine to which object to bind x() .

From your question I would expect code like this

void main() {
 new B();
}

abstract class A {
  A() {
    a();
    b();
    c();
  }
  a();
  b();
  c();
}

class B extends A {
  B() : super();

  @override
  a() => print('a');
  @override
  b() => print('b');
  @override
  c() => print('c');
}

Try in DartPad

From your comment about getting an error I expect you don't have the abstract method stubs in the base class. Maybe this is what you are looking for

void main() {
 new B();
}

@proxy
abstract class A {
  A() {
    a();
    b();
    c();
  }
}

class B extends A {
  B() : super();

  a() => print('a');
  b() => print('b');
  c() => print('c');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM