kotlin接口,伴生对象(静态or非静态)的笔记

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
伴生对象实例方法
伴生对象静态方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值