DEV Community

Stone
Stone

Posted on

kotlin learning notes Ⅲ——extend

Constructor

sub-class have primary constructors

If the subclass has a primary constructor, the base class must be initialized immediately in the primary constructor.

open class Person(var name : String, var age : Int){// base class

}

class Student(name : String, age : Int, var no : String, var score : Int) : Person(name, age) {

}

// test
fun main(args: Array<String>) {
    val s =  Student("Runoob", 18, "S12346", 89)
    println("name: ${s.name}")
    println("age: ${s.age}")
    println("number: ${s.no}")
    println("scpre: ${s.score}")
}

output:

name: Runoob
age: 18
number: S12346
score: 89

sub-class have no primary constructors

If the subclass does not have a primary constructor, the base class must be initialized with the super keyword in each secondary constructor, or proxy for another constructor. When initializing a base class, you can call different constructors of the base class.

class Student : Person {

    constructor(ctx: Context) : super(ctx) {
    } 

    constructor(ctx: Context, attrs: AttributeSet) : super(ctx,attrs) {
    }
}

example

/**base class**/
open class Person(name:String){
    /**secondary constructor**/
    constructor(name:String,age:Int):this(name){
        //initialize
        println("------super class secondary constructor-------")
    }
}

/**sub-class extends Person class**/
class Student:Person{

    /**secondary constructor**/
    constructor(name:String,age:Int,no:String,score:Int):super(name,age){
        println("-------sub-class secondary constructor---------")
        println("name: ${name}")
        println("age: ${age}")
        println("number: ${no}")
        println("score: ${score}")
    }
}

fun main(args: Array<String>) {
    var s =  Student("Rango", 18, "S12345", 89)
}

output

------super class secondary constructor-------
------sub-class secondary constructor-------
name: Rango
age: 18
number: S12345
score: 89

override

In the base class, when you use fun to declare a function, the function defaults to final decoration and cannot be overridden by subclasses. If subclasses are allowed to override the function, you need to manually add open to decorate it, and the subclass override method uses the override keyword
example

/**super class**/
open class Person{
    open fun study(){       // allow overridden
        println("I am Person Clss")
    }
}

/**sbuclass extend Person class**/
class Student : Person() {

    override fun study(){    // override function
        println("I am student class")
    }
}

fun main(args: Array<String>) {
    val s =  Student()
    s.study();

}

output

I am student class

Top comments (0)