Kotlin之对象表达式、声明、类代理

package net.edaibu.kotlintest.ClassAndExtends

/**
 * @author geqipeng
 *
 * @date 2017/5/26
 *
 * @time 18:35
 */
//对象表达式 和声明

//对象表达式
open class Test1(x: Int) {
    public open val x: Int = x
}

interface Interface1 {
    fun MethodTest() {
        println("测试接口")
    }
}

//类继承Test1
val testMethod = object : Test1(10) {
    override val x = 10
}


//对象声明 和java类似
object Animals {
    fun eat() {
        println("猫吃鱼")
    }

    fun play() {
        println("爬树")
    }
}


//伴随对象 companion关键字
class CompanionTest {
    companion object InnerObject {
        fun MethodCompanion(): CompanionTest = MethodCompanion()
    }
}

//伴随对象成员  通过类名做限定词直接使用
val companionMember = CompanionTest.MethodCompanion()


//使用companion关键字对象名可以省略
class CompanionTest2 {
    companion object {

    }
}

//伴随对象可以实现接口
interface InterfaceCompanion<T> {
    fun CompanionTest3()
}

class CompanionTest4 {
    companion object : InterfaceCompanion<CompanionTest> {
        override fun CompanionTest3() {

        }

    }
}

/**
 * 对象表达式和声明的区别

 * 他俩之间只有一个特别重要的区别:

 *对象表达式在我们使用的地方立即初始化并执行的

 *对象声明是懒加载的,是在我们第一次访问时初始化的。

​ *伴随对象是在对应的类加载时初始化的,和 Java 的静态初始是对应的。

 */

//类代理
  interface mInterface{
    fun Method1()
}

class TestClass(val test:Int):mInterface{
    override fun Method1() {
        println(test)
    }

}
//通过对象i代理TestClass中的公共方法
class Derived(i:mInterface) :mInterface by i


fun main(args: Array<String>) {
    println(testMethod)  //输出对象值:net.edaibu.kotlintest.ClassAndExtends.KotlinTest3Kt$testMethod$1@7ea987ac


//无继承类
    val testMethod2 = object {
        val test1: Int = 20
        val test2: Int = 30
    }

    println(testMethod2.test1 + testMethod2.test2)  //50


    println("对象声明————————————————————————————————————————")

    println(Animals.eat())  //猫吃鱼
    println(Animals.play()) //爬树


    println("类代理________________________")
    val x=TestClass(10)
    println(x)                   // net.edaibu.kotlintest.ClassAndExtends.TestClass@5cad8086
    Derived(x).Method1()         // 10


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值