Kotlin学习笔记之接口
interface MyStudent{ /*********************** 接口中的属性 ************************/ val name:String // 1、接口中可以声明抽象属性,等待继承接口的类去赋值 2021/6/22 val propertyWithImplementation:String // 2、带有访问器实现的属性 2021/6/22 get() { // return field // 3、接口中声明的属性的访问器中不能访问field字段(Property in an interface cannot have a backing field) 2021/6/22 return "Tom" } fun helloWorld(){ print(name) } /*********************** 接口中的方法 ************************/ fun study() // 4、接口中可以声明抽象方法,即只有方法声明,没有方法体的方法 2021/6/22 fun run(){ // 5、 接口中可以定义实现了方法体的方法 2021/6/22 print("run fast") } } // 6、实现1,在主构造函数中初始化属性 2021/6/22 class Tom(override val name: String) :MyStudent{ override fun study() { print(name + "不喜欢学习") } } // 7、实现2,通用实现 2021/6/22 class John : MyStudent{ override val name: String get() = "John" override fun study() { println(name + "喜欢学习") } } // 接口的继承 2021/6/22 interface Student:MyStudent{ override val name: String get() = "新接口中定义的覆盖的名称" } // 多接口继承时的覆盖冲突问题 2021/6/22 interface A{ fun methodA() fun methodB(){ println("这是接口A中的方法methodB") } } interface B{ fun methodA(){ println("这是接口B中的方法methodA") } fun methodB(){ println("这是接口B中的方法methodB") } } class C:A,B{ override fun methodA() { // 8、只有接口B实现了methodA,所以不存在冲突问题,所以一下两种写法等价 2021/6/22 super<B>.methodA() super.methodA() } override fun methodB() { // 9、接口A和接口B都实现了methodB,所以在调用时,需要指定是调用哪个接口的methodB 2021/6/22 super<A>.methodB() super<B>.methodB() } } // 10、接口的使用 2021/6/22 val anna = object : Student { override fun study() { println(name + "学习很努力") } }
作者:哈喽呀
链接:https://juejin.cn/post/7026624895706464293