[] Kotlin Kotlin commissioned (by using the keyword interface commission)



I. Define and implement a common interface



1. Ordinary defined interface: use the interface statement interface interface methods no method body, and without the abstract keyword modification;

package entrust

/**
 * 定义一个学习接口 , 代表有学习的能力
 */
interface IStudy {

    /**
     * 抽象方法 , 学习
     */
    fun study()

}

2. implement the interface: Use ":" Statement class implements the interface is a subclass of the interface, note that the class must implement the interface method implementation method requires the use of override modification;

package entrust

/**
 * 定义学生类 , 实现学习接口 , 其有学习的能力
 */
class Student : IStudy {

    /**
     * 实现的学习抽象方法
     */
    override fun study() {
        println("学习")
    }
}


II. Use delegate implements the interface



Use delegate implements the interface: using the : IStudystatement IStudy class implements the interface, but this class does not implement study () abstract method, but delegates to the Student class, when calling the study BadStudent () method is invoked automatically Study Student class () method;

package entrust

/**
 * 坏学生不学习 , 虽然实现了学习接口 , 但是其委托 普通学生来学习 , 自己什么都不做
 */
class BadStudent : IStudy by Student() {
}


III. To perform additional operations based on the use of the delegate implements the interface



Using delegates implement additional operations performed on the basis of the interface: when the class implements the interface, and the interface operation entrusted to another class, while still interface method may be implemented, in the process of rewriting, the method may delegate is invoked, and may additionally perform other operations;

package entrust

/**
 * 最好的学生
 * 委托 学生学习 , 自己额外学习更多东西
 */
class BestStudent : IStudy by Student() {

    /**
     * 委托其它类后 , 也可以自己实现该类 , 在委托方法的前后可以执行其它额外操作
     */
    override fun study() {

        println("复习之前的知识")

        Student().study()

        println("加强学习")

    }

}


. IV above three test interface (common implementation | commission | commissioned + additional operations)



Testing these three conditions:


① test interface class;

② test commissioned;

③ Test delegate additional other operations simultaneously;

package entrust

fun main() {

    // I . 测试接口实现类

    //创建 接口实现类 对象
    var goodStudent : Student = Student()

    //执行实现的内容
    //  学习
    goodStudent.study()


    // II . 测试委托

    // 创建 使用委托实现接口 类的对象
    var badStudent : BadStudent = BadStudent()

    //执行委托的方法
    //  学习
    badStudent.study()


    //III . 测试委托的同时额外执行其它操作

    //创建 使用委托实现接口并执行额外操作 类的对象
    var bestStudent : BestStudent = BestStudent()

    //执行委托方法和额外操作
    /*
        复习之前的知识
        学习
        加强学习
     */
    bestStudent.study()

}
Published 307 original articles · won praise 1043 · Views 1.7 million +

Guess you like

Origin blog.csdn.net/han1202012/article/details/105001048