4

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?

0

2 Answers 2

4

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().

Sign up to request clarification or add additional context in comments.

1 Comment

I used first way. Thanks.
1

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.

2 Comments

It is not possible to not shown method3() in child class? Means If needed then method3() overrided @EduardHasanaj
No it is not possible to hide it completely. However you may decompose class A in classes that represents method1, method2, method3 and use implements to not extend but use their interface. @sayreskabir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.