kotlin半生对象_Kotlin程序| 随播对象特征
kotlin半生對(duì)象
伴侶對(duì)象 (Companion object)
If you need a function or a property to be tied to a class rather than to instances of it (similar to static in java), you can declare it inside a companion object:
如果需要將函數(shù)或?qū)傩越壎ǖ筋惗皇菍?shí)例(類似于java中的static),則可以在同伴對(duì)象中聲明它:
You can omit the name, in which case the name defaults to Companion,
您可以省略名稱,在這種情況下,名稱默認(rèn)為Companion,
companion object <Optional Name>{//Companion Object Body }Companion objects members can only be accessed via the containing class name, not via instances of the class.
伴侶對(duì)象成員只能通過(guò)包含的類名稱訪問(wèn),而不能通過(guò)類的實(shí)例訪問(wèn)。
A class has only one companion object.
一個(gè)類只有一個(gè)伴隨對(duì)象。
Companion object initializes when class is loaded, (typically when first time reference from other code).
伴侶對(duì)象在加載類時(shí)初始化(通常是在第一次從其他代碼引用時(shí))。
Companion object has its own init block.
伴隨對(duì)象具有其自己的init塊。
The companion object is a singleton.
伴隨對(duì)象是單例。
Kotlin中的伴隨對(duì)象特征程序 (Program for companion object features in Kotlin)
package com.includehelp//Declare class class Car{//class init blockinit {println("Init Block of Class")}//Make companion objectcompanion object {//companion object init blockinit {println("Init Block of Companion object")}//property of companion objectval name="Tata Altroz !! "//function in companion objectfun printName(){println("Your Car name : $name")}} }//Main Function, Entry Point of Program fun main(){//Call method with Class name, //without create Instance of class, //like static method in javaCar.printName()//access Property using class nameval nameLen = Car.name.lengthprintln("Car Name Length : $nameLen") }Output:
輸出:
Init Block of Companion object Your Car name : Tata Altroz !! Car Name Length : 15翻譯自: https://www.includehelp.com/kotlin/companion-object-features.aspx
kotlin半生對(duì)象
總結(jié)
以上是生活随笔為你收集整理的kotlin半生对象_Kotlin程序| 随播对象特征的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java clock计时_Java Cl
- 下一篇: 程序员简历工作模式_简历的完整形式是什么