存取修飾子

四種存取修飾子

  • public
  • private
  • protected
  • internal 只能在同一個module中存取。

屬性

在屬性前面加上存取修飾子。

1
2
3
class Cat4 {
    private var age:Int = 0
}

在set前面加上存取修飾子,代表不允許其它地方設值,只有本身的類別可以設值。

1
2
3
4
5
6
class Cat4 {
    var name:String = ""
        private set(value) {
            field = value
        }
}

可簡化為:

1
2
3
4
class Cat4 {
    var name:String = ""
        private set
}

方法

在fun前面加上存取修飾子。

1
2
3
4
5
class Cat4 {
    protected fun run() {

    }
}

建構子

1
2
open class Parent protected constructor (val name: String) {
}

類別

1
2
internal open class Parent {
}

results matching ""

    No results matching ""