[] Kotlin Kotlin abstract classes and interfaces (interface declaration | abstract class declaration and implementation | interface)



I. The definition and implementation of Kotlin Interface



. 1 Kotlin definition of the interface:

/**
 * 定义接口
 */
interface IStudent{

    //声明抽象方法
    fun study()

}

. 2 Kotlin interface:

/**
 * 如果类实现一个接口 , 那么必须全部实现接口中的方法
 * 抽象类实现一个接口 , 可以不实现接口中的方法
 */
class MaleStudent : IStudent{

    /**
     * 实现 / 重写抽象方法 需要在方法关键字 fun 前添加 override 关键字
     */
    override fun study() {
        println("男学生学习")
    }

}

3 test interface and implementation class:

//创建接口的实现类对象
var maleStudent : MaleStudent = MaleStudent()

//男学生学习
maleStudent.study()


II. Kotlin abstract class defines



Kotlin definition of abstract class:

/**
 * 抽象类 : 只有抽象类中才能定义抽象方法 ( 与 Java 不同 )
 */
abstract class Human ( var name:String , var age:Int ) {

    /**
     * 定义抽象方法 , 类必须是抽象类
     */
    abstract fun say();

}


III. Kotlin class inherits the abstract class and implements the interface



. 1 Kotlin class inherits the abstract class and implements the interface:

/**
 * 接口 : 表现事物的能力 , 只能有方法
 * 抽象类 : 表现事物的本质 , 可以有成员和抽象方法
 *
 * 该类继承抽象类 , 实现接口
 */
class HumanStudent(name : String, age : Int) : Human(name , age), IStudent{

    override fun say() {
        println( "" + age + "岁的人类学生" + name + "在说话")
    }

    override fun study() {
        println("人类学生在学习")
    }

}

2. Test Interface + abstract class: HumanStudent inherits the abstract class interface implementation class;

// 测试 接口 + 抽象类

//HumanStudent 继承了 Human 抽象类 , 实现了 Student 接口
var humanStudent : HumanStudent = HumanStudent("Tom", 18);

//18岁的人类学生Tom在说话
humanStudent.say();

//人类学生在学习
humanStudent.study();


IV. Kotlin subclass of abstract class interface test



1 Interface: the ability to show things, there can be only method

2 abstract class: the performance of the nature of things, and members can have abstract methods


// 3 . 将 接口 实现类放到集合中

var students = listOf<IStudent>(maleStudent, humanStudent);

//循环遍历集合 
for(student in students){
    if(student is Human){
        //18岁的人类学生Tom在说话
        student.say()
    }
    if(student is IStudent){
        //人类学生在学习
        student.study()
    }
}
Published 307 original articles · won praise 1043 · Views 1.7 million +

Guess you like

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