Flutter: Optional method implementation in child class

Viewed 686

I have abstract class . Inside A class I have for example 3 methods:

abstract class A {
 @protected
 void method1()

 @protected
 void method2()

 @protected
 void method3()
}

Now,Class B is extended from A:

class B extends A {
@override
method1(){}

@override
method2(){}

@override
method3(){}// be optional 
}

I want to not force class B to implement all protected method in class A. For example I want to child class forced to implement 2 methods of 3 methods of class A and one method be obtional.

How can I implemented on flutter?

2 Answers

You can achieve the required behaviour in two ways :

First :

abstract class A {
  void method1();

  void method2();
  
  void method3 () {
    //default implmentation or empty body
  }
}

class B extends A {
  @override
  method1() {}

  @override
  method2() {}
}

Second :

abstract class A {
  void method1();

  void method2();
}

abstract class A1 extends A {
  void method3();
}

class B extends A1 {
  @override
  method1() {}

  @override
  method2() {}
}

This way you only get warning when you're class extends A1 class without implementing method3().

In such case you need to define an empty body to the methods of the base class.

abstract class A {
 @protected
 void method1() {}

 @protected
 void method2() {}

 @protected
 void method3() {}
}

I suggest you to throw an error like NotImplemented in the body of the methods just to notify you in case you have forgot to implement functionality and you are calling it.

Related