空的构造函数会被创建吗,即使已经显式地编写了另一个构造函数?

huangapple go评论78阅读模式
英文:

Does empty constructor is created although another constructor was explicitly written?

问题

我在Kotlin中是新手(对Java有一些经验)。
在Java中,如果我们至少编写了一个构造函数,编译器就不会生成任何空构造函数。只有在没有编写构造函数的情况下,才会生成空构造函数。
我知道在Kotlin中,编译器的工作方式与Java相同。
我在Kotlin中编写了一个带有一个参数的超类(名为Animal)构造函数。
此外,我为Animal编写了一个子类,子类调用了Animal的一个空构造函数。我不明白为什么编译器不会通知我这是一个编译错误,因为Animal类没有可调用的空构造函数。
我的代码:

open class Animal(val str: String = "sav") {
    open var fff: String = ""
    open var image = ""
    open val food = ""
    open val habitat = ""
    var hunger = 10

    open fun makeNoise() {
        println("The animal is making noise")
    }
}

class Hippo(var strrr: Int = 7) : Animal() {
    override var image = "hippo.jpg"
    override var food = "grass"
    override val habitat = "water"

    override fun makeNoise() {
        println("Grunt! Grunt!")
    }
}

Hippovar strrr: Int = 7):Animal() 不是一个问题吗?

英文:

I'm new in Kotlin (have some experience with Java).
In java, if we writing at least one constructor so the compile won't build any empty constructor. Empty constructor will be build only if we didn't write a constructor.
I know that in Kotlin, compiler also working the same as in Java.
I wrote in Kotlin a super class (with the name Animal) with a constructor with one parameter.
In addition i wrote a sub class for Animal, and the subclass calls an empty constructor of Animal. I can't understand why compiler doesn't inform me that it is a compile error since Animal class doesn't have an empty constructor to be called.
My code:

    open class Animal (val str:String = "sav")
{
    open var fff:String = ""
    open var image = ""
    open val food =""
    open val habitat =""
    var hunger = 10

     open fun makeNoise()
    {
        println("The animal is making noise")
    }
}

class Hippo ( var strrr:Int = 7) : Animal()
{
    override var image = "hippo.jpg"
    override var food = "grass"
    override val habitat = "water"



    override fun makeNoise()
    {
        println("Grunt! Grunt!")
    }
}

> class Hippo ( var strrr:Int = 7) : Animal()> isn't a problem?

答案1

得分: 3

按照文档所述:

> 在 JVM 上,如果主构造函数的所有参数都具有默认值,则编译器将生成一个额外的无参数构造函数,该构造函数将使用默认值。

顺便说一下,这个构造函数在 Java 中也是可见的。

英文:

As documentation states:

> On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values.

By the way, this constructor will be visible from Java too.

huangapple
  • 本文由 发表于 2020年10月12日 03:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64308287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定