Kotlin study notes (IV): Classes and Objects of Kotlin

I. Introduction

KotlinUsing the keyword classdeclaring class, followed by the class name. KotlinThe class is the default public final, so if you do not like is finalwhen the need to use openkeywords to decorate a class, if not declare the parent class. The default is the parent Anyclass.

//定义一个空类
open class Animal

interface Run

//继承类或接口时,使用 : 隔开,父类和接口间使用 , 隔开
class Dog : Animal(), Run

Second, a constructor

1. Main constructor

After the constructor on the main class name can not contain any code, the code can be placed in the initialization code segment initialization, initialization code segment using the initkeyword as a prefix.
注意:Primary constructor parameter may be used in the initialization code segment may be defined by the properties and the primary constructor initializes attribute value (which may be varor val).

class Dog constructor(val age: Int, val name: String){

    init {
        println("Dog $name is $age years old.")
    }

}

If the constructor annotated, or have visibility modifier, constructorthe keyword is necessary, notes and modifiers placed before it, otherwise it constructorcan be omitted.

2. Create an instance of

fun main(args: Array<String>) {
    val dog = Dog(2,"Irving")
}

3. Secondary Constructor

Secondary constructor class using constructormodified.

class Cat {
    
    constructor(age: Int, name: String){
        println("Cat $name is $age years old")
    }
    
}

If the main class constructor, then each constructor need secondary agent directly or indirectly, this master builder. Acting another constructor in the same class using thiskeywords.

class Cat(age: Int) {

    constructor(age: Int, name: String): this(age){
        println("Cat $name is $age years old")
    }

    constructor(age: Int, name: String, type: Int): this(age, name){
        println("Cat $name is $age years old")
    }
    
}

Third, access modifier

  1. private:Modified class, the class represents all members are private. When modifying members, it indicates that the class members are private.
  2. protected:Can only be used to modify the members of the class, he said that only the class and its subclasses can access the member.
  3. public:All classes are accessible.
  4. internal:Indicates only that the modules ( moudleclasses in) access.

Fourth, the associated objects

By companion objectstatement accompanying the object must be written within a class, as a companion object of this class, the compiler will generate a compile-time static in the class Companionobject and then call the members of this static object. Associated object properties and methods can be understood as Javathe static variables and methods, it can be directly 类名.属性/方法invoked, if it is Javathrough the call class 类名.Companion.属性/方法calls

	class Bird{

	    companion object {
	        const val BIRD_NAME = "Irving"
	
	        fun getBirdName(): String = BIRD_NAME 
	    }

	}

In addition to using objectkeyword to declare a singleton class outside, using the companion object can easily create singleton object.

	class Person{
	
	    companion object {
	        fun get(): Person = Holder.instance
	    }
	
	    private object Holder{
	        val instance = Person()
	    }
	
	}

Five, Kotlin dynamic proxy

KotlinBy using byeasy to use dynamic proxy keyword.

interface People {
    fun sayHello()
}

//目标类
class Man : People {
    override fun sayHello() {
        println("Hello")
    }
}

//代理类
class Irving(people: People) : People by people 

fun main(args: Array<String>) {
    val irving = Irving(Man())
    irving.sayHello()
}

KotlinWill be compiled as dynamic static proxy agent to call, so Kotlinthe dynamic proxy than Javahigh dynamic proxy efficiency, because Javathe dynamic nature of the agent is through reflection to call.

Sixth, data classes

You can use datakeyword to declare a data type, the data class is public final, it may not be inherited (seal type may be used if desired inheritance). The compiler will generate data for all the attributes of the class getter()/setter()methods, and will rewrite toString(), hashCode(), equals(), copy()of these methods.

data class User(
    var id: Int,
    var name: String,
    var gender: Int
)

Seven, sealed class

Sealed classes can be understood as an enhanced enumeration class, sealed class and its subclasses must be written in the same file, the enhanced sealing place is a subclass of class can be extended to more flexible.

sealed class Hello {
    object UP : Hello()
    object DOWN : Hello()
    object LEFT : Hello()
    object RIGHT : Hello()
    class Irving(var age: Int) : Hello()
}

fun test(hello: Hello) {
    when (hello) {
        Hello.UP -> println("UP")
        Hello.DOWN -> println("DOWN")
        Hello.LEFT -> println("LEFT")
        Hello.RIGHT -> println("RIGHT")
        is Hello.Irving -> println(hello.age)
    }
}

fun main(args: Array<String>) {
    test(Hello.Irving(11))
}
Published 167 original articles · won praise 230 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_39240270/article/details/104179107