djalmafreestyler
djalmafreestyler

Reputation: 1909

Dart - Is it possible to prevent implementation of method that is not in interface

Is it possible to prevent implementation of method that is not in interface, for example:

abstract class IController {

void add();

}

class Controller implements IController {

@override
void add();

// Should not allow this, 
// methods that is not present in the interface
void addMore();

}

Upvotes: 1

Views: 825

Answers (2)

lrn
lrn

Reputation: 71663

It is not possible.

An interface is a contract. If you satisfy the contract, you're allowed to implement the interface. Any code which expects something implementing the interface can use your code because it is compatible with the interface.

You can have any other members, there is no functionality to prevent that. You won't be able to call those other members when all you know about the object is that it implements IController (when that's the type of the variable the value is stored in).

Why do you want to prevent subclasses from adding their own members?

Upvotes: 1

pedro pimont
pedro pimont

Reputation: 3084

I don't think you can do it. But there's a hack to achieve that.

abstract class IController {
  factory IController() {
    return _Controller();
  }
  
void add();
}

class _Controller implements IController {  

  @override
  void add() {}

  void addMore() {}
}

Putting those two classes alone in the same file, only IController will have access to _Controller because we turned it in a private class using _ so now, with the factory constructor inside IController, you can call it whenever you like and will only have access to the interface IController and its methods.

Upvotes: 0

Related Questions