A
A
Arkady Vinogradov2021-03-10 14:09:23
Kotlin
Arkady Vinogradov, 2021-03-10 14:09:23

Why specify the interface type when creating a class object?

6048a88665cee007039726.png

Screenshot code:

interface Do {
    fun doing ()
}

class Teacher() : Do {
    override fun doing () {
        println("Im teaching students..")
    }
}

class Programmer() : Do {
    override fun doing() {
        println("Im writing programs..")
    }
}

fun main() {

    val person1: Do = Programmer()
    person1.doing()

    val person2: Programmer = Programmer()
    person1.doing()

}


We have an interface in which there is an abstract doing method for implementing classes that inherit this interface, when creating a class object that inherits this interface, we can specify the type of both the class and the type of the interface, the question is, is there any difference what type to specify?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2021-03-10
@usov-dmitriy

In such a primitive example, there is no difference.
But if there is a function that accepts Do, it will be possible to pass an object of any Do subclass into it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question