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
}