Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

dart - Flutter: Optional method implementation in child class

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?

question from:https://stackoverflow.com/questions/65858496/flutter-optional-method-implementation-in-child-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...