kotlin接口的笔记,如何用类C实现了相同名字的方法的接口和继承相同名字方法的接口,使用super关键字
interface A{
fun method(){
println("我是A")
}
}
open class B{
open fun method() {
println("我是B")
}
}
//C继承了B,实现了A
class C : A, B() {
override fun method() {
super<A>.method()
super<B>.method()
}
}
fun main(args: Array<String>) {
val c = C()
c.method()
}
output:
我是A
我是B
对象的声明还有伴生对象作为类的内部类的分析
//对象声明
object MyObject {
fun say() {
println("我是一个对象")
}
}
fun main(args: Array<String>) {
MyObject.say()
println("")
Tree3.say()
println(Tree3.seed)
println("")
//不用构建实例对象,即可直接调用伴生对象
val t = Tree3.Companion
//输出伴生对象实例,是Tree3的内部类
println(t.javaClass)
//调用伴生对象的两种形式的方法,可通过反编译查看
// 其Trees对象的结构,静态or非静态方法,属性
//@Jvmstatic注解实现非静态到静态的转变
//当然,调用实例或调用静态方法在Kotlin里是一样的
Trees.mehthod()
Trees.mehthod2()
}
//伴生对象
class Tree3 {
companion object {
var seed:Int = 100
fun say() {
println("我是树的伴生对象")
}
}
}
class Trees {
companion object {
fun mehthod() {
println("伴生对象实例方法")
}
@JvmStatic
fun mehthod2() {
println("伴生对象静态方法")
}
}
}
output:
我是一个对象
我是树的伴生对象
100
class com.haha.Interface.Tree3$Companion
伴生对象实例方法
伴生对象静态方法