kotlin singleton object declaration and

1. Concept

Object declaration is designed to create a singleton used.

Syntax:

object ObjectName : [0-N个父类型] {
    //对象声明类体
}

2. Features (comparison object expression)

  • Object expression is an expression, an object can be used to assign --- statement is not an expression, not for assignment;
  • Expression can include internal objects classes, but can not contain a nested class declarations can include objects --- nested classes, but can not contain internal class;
  • Exclusive expression can be defined as a local variable (i.e. defined in the method / function) --- declared objects can not be defined in the method / function;
  • Object expression requires access to the object by object expression variable declaration statement --- because the object has a name, so you can access the object directly through the name of the object declaration.

3. Define the object declaration

fun main() {
    println(Badminton.name)//羽毛球

    println(Running.name)//短跑
    Running.playRules()//在跑道上比赛

    println(Basketball.name)//篮球
    println(Basketball.isBelongSports)//true

    Basketball.playRules()//在篮球场比赛
    println(Basketball.FamousPlayers(ArrayList(listOf("乔丹", "科比", "詹姆斯"))).players)//[乔丹, 科比, 詹姆斯]
}

/**
 * 定义一个运动接口
 */
interface Sports {
    val name: String
}

/**
 * 定义一个球类抽象类
 */
abstract class Ball(val isBelongSports: Boolean) {
    abstract fun playRules()
}

object Badminton : Sports {
    override val name: String
        get() = "羽毛球"
}

object Running {
    val name: String

    init {
        name = "短跑"
    }

    fun playRules() {
        println("在跑道上比赛")
    }
}

object Basketball : Ball(true), Sports {
    override val name: String
        get() = "篮球"

    override fun playRules() {
        println("在篮球场比赛")
    }

    /**
     * 可以定义嵌套类,但不能定义内部类
     */
    class FamousPlayers(val players: ArrayList<String>)
}

4. Singleton object declaration and

Object declaration designed to create single-case model, because the object declaration defines the object object declaration is the only instance of the class can be instantiated by name directly access the object.

fun main() {
    println(Singleton.name)//勒布朗詹姆斯
    Singleton.name = "科比布莱恩特"
    println(Singleton.name)//科比布莱恩特
}

object Singleton {
    var name = "勒布朗詹姆斯"
}

Guess you like

Origin www.cnblogs.com/nicolas2019/p/10960160.html