【问题标题】:Calling Secondary constructor to Secondary Constructor in Kotlin在 Kotlin 中调用辅助构造函数到辅助构造函数
【发布时间】:2019-07-01 17:36:48
【问题描述】:

我是 Kotlin 的 OOP 新手。我在 Java 方面有很强的基础。但我正面临这个尚未解决的问题。

这是java代码:-

public class Parent {
    String name;
    int age;
    boolean isAlive;

    Parent(String name, int age) {
        this.name = name;
        this.age = age;
    }

    Parent(boolean isAlive) {
        this.isAlive = isAlive;
    }
}

final class Child extends Parent {

    Child(String name, int age) {
        super(name, age);
    }

    Child(boolean isAlive) {
        super(isAlive);
    }
}

我不知道如何在 Kotlin 中编写这段代码。如何从子二级构造函数中调用父二级构造函数?

【问题讨论】:

    标签: object kotlin


    【解决方案1】:

    不就是这样

    class Child: Parent {
        constructor(name: String, age: Int): super(name, age)
        constructor(isAlive: Boolean): super(isAlive) 
    }
    

    【讨论】:

    • 非常感谢。我认为 Kotlin 中的每个类都需要有一个主构造函数。
    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2017-03-12
    相关资源
    最近更新 更多