Gladi
Gladi

Reputation: 425

Kotlin Inheritance question - inherenting class type cast

Suppose i have the class:

open class Organism {
    open fun saySomething(){
        print("Nein")
    }
}

And the inheriting class:

class Person : Organism() {
    override fun saySomething() {
        println("Saying hello")
    }
}

Why when i run this code, i still get the person implementation:

 val x = Person()
 (x as Organism).saySomething()  // Output: Saying hello

This casting shouldn't run the Organism class implementation??

Thanks.

Upvotes: 0

Views: 259

Answers (1)

Taseer
Taseer

Reputation: 3502

No, it should not. It is because you are yourself telling the compiler that you are overriding Organism class method and the compiler should use this overridden method over the super(Parent class method) implementation. If you want to call super behavior of the parent, then in the overridden method in the child class, include super.saySomething() before or after the println() depending on your use. Also, if you write val x: Organism = Person(), this will compile because the Person makes is-a relationship with the Parent class and the compiler knows what to call in that case. This, in other words, called Polymorphism.

Upvotes: 2

Related Questions