zoukankan      html  css  js  c++  java
  • 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()
        }
    }
  • 相关阅读:
    python cookbook 笔记二
    python cookbook 笔记一
    aircrack-ng笔记
    TeamCity 和 Nexus 的使用
    Linux 搭建 nexus 私服【转】
    maven阿里云镜像
    kali linux 破解wpa密码
    python正则表达式二[转]
    Java并发编程:Synchronized底层优化(偏向锁、轻量级锁)
    集合解析
  • 原文地址:https://www.cnblogs.com/developer-wang/p/13176683.html
Copyright © 2011-2022 走看看