DEV Community

Stone
Stone

Posted on

kotlin learning notes Ⅱ—— class and object

class

Classes in Kotlin are declared using the keyword class:

class Runoob {  // class name is Runoob
    // .......
}

We can use constructors to create class instances just like normal functions

val site = Runoob() // in Kotlin ,there don't have new keyword

getter & setter

The following example defines a person class with two variable variables lastName and no. lastName modifies the getter method and no modifies the setter method:

class Person {

    var lastName: String = "zhang"
        get() = field.toUpperCase()   // Convert variable to uppercase
        set

    var no: Int = 100
        get() = field                
        set(value) {
            if (value < 10) {      
                field = value
            } else {
                field = -1       
            }
        }

    var heiht: Float = 145.4f
        private set
}

// test
fun main(args: Array<String>) {
    var person: Person = Person()

    person.lastName = "wang"

    println("lastName:${person.lastName}")  // output:lastName: Wang

    person.no = 9
    println("no:${person.no}") // output:no: 9

    person.no = 20
    println("no:${person.no}") // // output:no: -1

}

abstract class

Abstract members have no implementation in the class.
Note: there is no need to annotate an abstract class or member with an open annotation.

open class Base {
    open fun f() {}
}

abstract class Derived : Base() {
    override abstract fun f()
}

inner class

Inner classes are represented by the inner keyword.
The inner class will have a reference to the object of the outer class, so the inner class can access the external class member properties and member functions

class Outer {
    private val bar: Int = 1
    var v = "member property"
    /**inner class**/
    inner class Inner {
        fun foo() = bar  // outer class number
        fun innerTest() {
            var o = this@Outer 
            println("inner class can use outer class number,eg:" + o.v)
        }
    }
}

fun main(args: Array<String>) {
    val demo = Outer().Inner().foo()
    println(demo) //   1
    val demo2 = Outer().Inner().innerTest()   
    println(demo2)   //inner class can use outer class number,eg:member property
}

Top comments (0)