Kotlin类与对象

class MainActivity : AppCompatActivity() , View.OnClickListener
  • 默认的类都是 public final 修饰符修饰 如果需要不final 需要手动添加 open 修饰符

  • 构造函数添加参数,直接在类名后面添加即可

class MainActivity( val int: Int) : AppCompatActivity() , View.OnClickListener 
  • 使用类的构造函数的参数
init {
        println("jia $int")
    }
  • 次构造函数
class TextView : View {

    constructor(context: Context) : super (context) {
    }

    constructor(context: Context, attrs: AttributeSet?) : this (context, attrs, 0) {
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super (context, attrs, defStyleAttr) {
    }

}
  • 访问修饰符


    Kotlin类与对象_第1张图片
    image.png
  • internal Kotlin特有
    表示一个模块内下的可以使用

Kotlin类与对象_第2张图片
image.png

伴生对象

  • Java中类方法实现


    Kotlin类与对象_第3张图片
    image.png
  • Kotlin怎么实现?因为Kotlin是没有静态类的,实现方法有两种,第一种,注解。第二种 伴生对象


class StringUtils {
    companion object {
        fun isEmpty(str: String) : Boolean {
            return "" == str
        }
    }
}

        StringUtils.isEmpty("")

  • Java怎么调用使用Kotlin写的伴生对象?
        StringUtils.Companion.isEmpty("");
  • 单例类
package com.example.kotlindemo

class Single private constructor(){
    companion object {
        fun get(): Single {
            return Holder.instance
        }
    }

    private object Holder {
        val instance = Single()
    }
}

        Single.get()

  • 动态代理
  • Kotlin特有的类

你可能感兴趣的:(Kotlin类与对象)