dominicm00
dominicm00

Reputation: 1600

Force subclass to implement abstract override method

I have an abstract class with some abstract methods that subclasses need to implement.

abstract class BlockData {
  Widget build();

  BlockData get value;
}

class NumberData extends BlockData {

  NumberData(Function updateCallback) : super(updateCallback);

  // trying to remove either of the below methods throws a compiler error as expected
  @override
  BlockWidget build() {
    // TODO: implement build
    throw UnimplementedError();
  }

  @override
  BlockData get value => this;
}

As expected, my subclass is forced to implement them. However, I also want to force my class to implement a custom == and hashcode method. When I override these methods in my abstract class with an abstract implementation, they are completely ignored and the subclass is allowed to not implement them.

abstract class BlockData {
  Widget build();

  BlockData get value;

  @override
  bool operator ==(other);

  @override
  int get hashCode;
}

// this should throw an error since it doesn't implement == or hashcode, but it doesn't
class NumberData extends BlockData {

  NumberData(Function updateCallback) : super(updateCallback);

  @override
  BlockWidget build() {
    // TODO: implement build
    throw UnimplementedError();
  }

  @override
  BlockData get value => this;
}

This is different from the behavior in Java, where you can make an abstract method that overrides a superclass and force a subclass to have a custom implementation. Is there any way to force this in Dart, and for that matter, is this expected behavior?

Upvotes: 2

Views: 5294

Answers (2)

MSOB7Y
MSOB7Y

Reputation: 31

you can just do like

FutureOr<void> myFunction();

and it will force any inheritor to override it.

Upvotes: 3

Related Questions