Kotlin constructor Research

Kotlin constructor Research

Introduction:
When I learned of the constructor kotlin, some say online book doubts.
I do not know what they have said is not accurate enough and perfect, or my cognitive errors.
I have the following to say different opinions, please Gangster criticism (if someone saw my article, then, a head).

1 has only one primary constructor

My view: You can not have a primary constructor, only 0 to the plurality of sub-constructors
first clear written regarded as the main constructor where - at the head of the class (class header) and not in the class body (class body).
For example such a case, there is no main construction method, only one secondary configuration method:

//没有主构造方法,只有一个副构造方法
class Human1{
    //在类体中写的副构造方法
    constructor(name: String)
}

This code idea is only a warning, said to be written in the format of the main construction method is recommended, but you can compile. This is not counted as kotlin main constructor can not allow it?

There is another situation: there is no main construction method, only a plurality of sub-construction method:

class Human2 {
    constructor(name: String) {
        println(name)
    }

    constructor(age: Int) {
        println(age)
    }

}

This code does not even give a warning in the idea.

2. Vice constructors must call the primary constructor

This problem is somewhat similar to the previous question,
in my opinion: Vice constructor can not call the primary constructor.
such as:

class Human3 {
    constructor(name: String) {
        println(name)
    }

    constructor(age: Int) {
        println(age)
    }

}

This is not because there is no primary constructor, there is no need to call the primary constructor do?
A look at the following example:

class Human4(){
    constructor(name: String) : this() {
        println(name)
    }

    constructor(age: Int) : this() {
        println(age)
    }
}

You can see, add an empty primary construction method on Human4 this class, you must call this leads to empty main constructor in the sub-constructor of the class.
This shows that, in the absence of the sub-main constructor constructor does not call the main constructor. (A bit like crap ??), but when the main constructor, you must call the primary constructor.

These conclusions are based only on my shallow understanding, welcome criticism.

Guess you like

Origin www.cnblogs.com/soclear/p/12590391.html