Search code examples
javakotlininheritanceconstructordefault-constructor

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


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?


Solution

  • 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.