Kotlin學習系列之:Kotlin的建構函式,kotlin建構函式

來源:互聯網
上載者:User

Kotlin學習系列之:Kotlin的建構函式,kotlin建構函式

    Kotlin的建構函式分為主構造器(primary constructor)和次級構造器(secondary constructor)。下面我們來看看他們的寫法。

一、Primary Constructor

1. 寫法一:

class 類名 constructor(形參1, 形參2, 形參3){}
eg: 

class Person constructor(username: String, age: Int){private val username: Stringprivate var age: Intinit{this.username = usernamethis.age = age}}
這裡需要注意幾點:
  • 關鍵字constructor:在Java中,構造方法名須和類名相同;而在Kotlin中,是通過constructor關鍵字來標明的,且對於Primary Constructor而言,它的位置是在類的首部(class header)而不是在類體中(class body)。
  • 關鍵字init:init{}它被稱作是初始化代碼塊(Initializer Block),它的作用是為了Primary Constructor服務的,由於Primary Constructor是放置在類的首部,是不能包含任何初始化執行語句的,這是文法規定的,那麼這個時候就有了init的用武之地,我們可以把初始化執行語句放置在此處,為屬性進行賦值。

2. 寫法二(演變一):

a. 當constructor關鍵字沒有註解和可見度修複符作用於它時,constructor關鍵字可以省略(當然,如果有這些修飾時,是不能夠省略的,並且constructor關鍵字位於修飾符後面)。那麼上面的代碼就變成:

class Person (username: String, age: Int){    private val username: String    private var age: Int    init{this.username = usernamethis.age = age    }}
b. 初始化執行語句不是必須放置在init塊中,我們可以在定義屬性時直接將主構造器中的形參賦值給它。
class Person(username: String, age: Int){    private val username: String = username    private var age: Int = age}
可以看出,我們的寫法二實際上就是對我們在寫法一前面提到的兩個關鍵字的簡化。

3.寫法三(演變二):
這種在構造器中聲明形參,然後在屬性定義進行賦值,這個過程實際上很繁瑣,有沒有更加簡便的方法呢?當然有,我們可以直接在Primary Constructor中定義類的屬性。
class Person(private val username: String, private var age: Int){}
如果類不包含其他動作函數,那麼連花括弧也可以省略
class Person(private val username: String, private var age: Int)

看,是不是一次比一次簡潔?實際上這就是Kotlin的一大特點

4.    當我們定義一個類時,我們如果沒有為其顯式提供Primary Constructor,Kotlin編譯器會預設為其產生一個無參主構造,這點和Java是一樣的。比如有這樣的一個類:

class Person {    private val username = "David"    private var age = 23    fun printInfo() {        println("username = $username, age = $age")    }}fun main(args: Array<String>) {    val person = Person()    person.printInfo()}
我們使用javap命令來反編譯這個Person類。可以看到這個無參主構造:


二、Secondary Constructor
1.樣本:

class User{private val username: Stringprivate var age: Intconstructor(username: String, age: Int){    this.username = username    this.age = age}}

和Primary Constructor相比,很明顯的一點,Secondary Constructor是定義在類體中。第二,Secondary Constructor可以有多個,而Primary Constructor只會有一個。

2. 要想實現屬性的初始化,實際上主構造器已經能夠應付多數情況了,為什麼還需要次級構造器?主要原因是因為我們有時候是需要去繼承架構中的類。如在Android中你自訂一個Button:
class MyButton : AppCompatButton {    constructor(context: Context) : this(context, null)    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, R.attr.buttonStyle)    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)}

在這種情況下,你如果需要重寫AppCompatButton的多個構造器,那麼,就需要用到Secondary Constructor。同樣,這裡也有幾點需要注意:

  • 可以看到,我們可以使用this關鍵字來調用自己的其他構造器,並且需要注意它的文法形式,次級構造器: this(參數列表)
  • 可以使用super關鍵字來調用父類構造器,當然這塊內容我們放到繼承那塊再來介紹。
3. 我們再來看這樣一種情況,我們同時定義了主構造器和次級構造器:
class Student constructor(username: String, age: Int) {    private val username: String = username    private var age: Int = age    private var address: String    private var isMarried: Boolean    init {        this.address = "Beijing"        this.isMarried = false    }    constructor(username: String, age: Int, address: String) :this(username, age) {        this.address = address    }    constructor(username: String, age: Int, address: String, isMarried: Boolean) : this(username, age, address) {        this.isMarried = isMarried    }}
可以看到,四個參數的次級構造調用三個參數的次級構造,而三個參數的次級構造又調用了主構造。換句話,次級構造會直接或者間接調用主構造。這也就是這個例子需要說明的問題。如果你還不信,我們可以把“: this(username, age)”刪除掉,看編譯器會給你什麼提示:

“Primary constructor call expected”。提示很明顯,和我們在之前提到的內容是一樣的。 查看評論

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.