• kotlin类和对象—>接口


    1.接口定义,使用关键字interface 来定义接口

    interface MyInterface { 
        fun bar()
        fun foo() {
            // 可选的方法体
        } 
    }

    2.实现接口,一个类和对象可以实现一个或多个接口

    class Child : MyInterface {
         override fun bar() {
            // 方法体
         }
    }

    3.接口中的属性,在接口中声明的属性要么是抽象的,要么提供访问器的实现。在接口中声明 的属性不能有幕后字段(backing field),因此接口中声明的访问器不能引用它们。

    interface MyInterface { 
            val prop: Int // 抽象的
            val propertyWithImplementation: String 
                    get() = "foo"
            fun foo() {
                 print(prop)
            }
    }
    
    class Child : MyInterface {
         override val prop: Int = 29
    }

    4.接口继承,一个接口可以从其他接口派生,从而既提供基类型成员的实现也声明新的函数与属性。很自然地,实现 这样接口的类只需定义所缺少的实现

    interface Named {
        val name: String
    }
    
    interface Person : Named {
        val firstName: String
        val lastName: String
        override val name: String get() = "$firstName $lastName"
    }
    
    data class Employee( // 不必实现“name”
            override val firstName: String,
            override val lastName: 
            String, val position: Position
    ) : Person

    5.覆盖冲突问题,实现多个接口时,可能会遇到同一方法继承多个实现的问题

    interface A {
        fun foo() {
            print("A")
        }
        fun bar()
    }
    
    interface B {
        fun foo() {
            print("B")
        }
        fun bar() {
            print("bar")
        }
    }
    class C : A {
        override fun bar() {
            print("bar")
        }
    }
    
    class D : A, B {
        override fun foo() {
            super<A>.foo()
            super<B>.foo()
        }
        override fun bar() {
            super<B>.bar()
        }
    }
  • 相关阅读:
    Linux的内存分页管理
    python3将汉字转换为大写拼音首字母
    linux下安装微信小程序开发工具
    有效使用Django的QuerySets
    VsCode快捷键
    js 里面的键盘事件对应的键码
    ubuntu下wps的安装
    mac 安装 python mysqlclient 遇到的问题及解决方法
    微服务初步理解
    有return的情况下try catch finally的执行顺序(最有说服力的总结)
  • 原文地址:https://www.cnblogs.com/developer-wang/p/13176683.html
Copyright © 2020-2023  润新知