can‘t be used as a mixin because it extends a class other than ‘Object‘.
IT object be Class can as than used
2023-09-11 14:14:53 时间
程序员如果敲一会就停半天,抱着一杯茶,表情拧巴,那才是在编程
前言 - 基础关键字
- class:声明一个类,提供具体的成员变量和方法实现。
- abstract class:声明一个抽象类,抽象类将无法被实例化。抽象类常用于声明接口方法、有时也会有具体的方法实现。
- mixin:声明一个Mixin类,与抽象类一样无法被实例化,是一种在多重继承中复用某个类中代码的方法模式,可以声明接口方法或有具体的方法实现。
- extends:继承,和其它语言的继承没什么区别。
- with:使用Mixin模式混入一个或者多个Mixin类。
- implements:实现一个或多个接口并实现每个接口定义的API。
- on:限制Mixin的使用范围。
1 错误信息
Error: The class ‘B’ can’t be used as a mixin because it extends a class other than ‘Object’.
class C extends A with B{
^
Error: Compilation failed.
2 测试核心代码
测试使用工具 dartPad
https://dartpad.dartlang.org/flutter
class A {
void run(){
print("a run");
}
}
class B extends A{
void run(){
print("b run");
}
}
class C extends A with B{
}
void main() {
C c = C();
c.run();
}
3 Dart with 关键字
关键字with表示使用了"Mixin"
mixin指的是将另一个或多个类的功能添加到您自己的类中,而不从这些类继承的能力.这些类的方法现在可以在类上调用,这些类中的代码将被执行.
Dart没有多重继承,但mixin的使用允许您在其他类中折叠以实现代码重用,同时避免多重继承可能导致的问题.
如下定义两个类A、B,分别有自己的方法,A与B分别是抽象的,不可直接创建实例:
abstract class A {
void run() {
print("a run");
}
void show(){
}
}
abstract class B {
void run() {
print("b run");
}
void eat() {
print("b eat");
}
}
再定义类C,要求C具备A与B的能力,可以定义如下:
class C extends A with B {
}
如果要使 B 再具备 A的能力:
abstract class A {
void run() {
print("a run");
}
void show(){
}
}
abstract class B extends A{
void run() {
print("b run");
}
void eat() {
print("b eat");
}
}
如果B再继承A,那么上述定义的类C就会出现异常
Error: The class ‘B’ can’t be used as a mixin because it extends a class other than ‘Object’.
class C extends A with B{
正确的做法:
abstract class A {
void run() {
print("a run");
}
void show() {
print("a show");
}
}
mixin B on A {
void run() {
print("b run");
}
void eat() {
print("b eat");
}
}
class C extends A with B {}
void main() {
C c = C();
c.run();
c.eat();
}
相关文章
- Java中泛型 Class<T>、T与Class<?>、 Object类和Class类、 object.getClass() 和 Object.class
- Does VS code have variable explorer object like we have it in spyder?
- 【IT运维小知识】安全组是什么意思?
- IT公司防止运维偷窥和篡改数据库的最佳武器-云堡垒机!
- 高德纳:2015十大战略性IT趋势
- UVa 658 It's not a Bug, it's a Feature! (状态压缩+Dijstra)
- Vue的报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
- 《IT运维之道》——第17章 天外有天:IT服务的国际标准17.1 ITIL
- 入坑IT十年(二)技术以外
- 那些令人喷饭的代码注释:仅以此代码献给...it's realy ?
- nvidia-smi failed because it couldn't communicate with the nvidia driver
- ASP.NET list<object> OBJECT.clean()会清空session['OBJECT']的值的问题
- IT必读:OA中如何制作转正申请单
- 杂(三)-The type java.lang.Object cannot be resolved It is indirectly referenced ...
- 双模式IT:企业IT部门是否能够肩负双重劳动力角色的概念?
- 2019年云IT基础设施的投入将达543亿美元
- IDC:2017年公有云和私有云将推动云IT基础设施支出增长
- 从IT时代转入DT时代 安防应该注意什么?
- 科普IT行业中时髦词汇:大数据