<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Kotlin 伴隨對象 > 原文: [https://www.programiz.com/kotlin-programming/companion-objects](https://www.programiz.com/kotlin-programming/companion-objects) #### 在本文中,您將借助示例學習在 Kotlin 程序中創建和使用伴隨對象。 在介紹伴隨對象之前,讓我們以訪問類成員的示例為例。 ```kt class Person { fun callMe() = println("I'm called.") } fun main(args: Array<String>) { val p1 = Person() // calling callMe() method using object p1 p1.callMe() } ``` 在這里,我們創建了`Person`類的對象`p1`來調用`callMe()`方法。 這就是正常情況下的工作方式。 但是,在 Kotlin 中,您還可以通過使用類名來調用`callMe()`方法,即在這種情況下使用`Person`。 為此,您需要通過使用`companion`關鍵字標記[對象聲明](https://www.programiz.com/kotlin-programming/object-singleton#object-declarations "Kotlin object declaration")來創建伴隨對象。 * * * ### 示例:伴隨對象 ```kt class Person { companion object Test { fun callMe() = println("I'm called.") } } fun main(args: Array<String>) { Person.callMe() } ``` 運行該程序時,輸出為: ```kt I'm called. ``` 在程序中,`test`對象聲明用關鍵字`companion`標記,以創建伴隨對象。 因此,可以通過使用以下類的名稱來調用`callMe()`方法: ```kt Person.callMe() ``` * * * 伴隨對象的名稱是可選的,可以省略。 ```kt class Person { // name of the companion object is omitted companion object { fun callMe() = println("I'm called.") } } fun main(args: Array<String>) { Person.callMe() } ``` * * * 如果您熟悉 Java,則可以將伴隨對象與靜態方法相關聯(即使它們在內部的工作方式完全不同)。 伴隨對象可以訪問該類的私有成員。 因此,它們可用于實現[工廠方法模式](https://stackoverflow.com/questions/69849/factory-pattern-when-to-use-factory-methods "Kotlin Factory Pattern")。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看