I
I
Igor-Novikov2020-04-17 16:37:42
Kotlin
Igor-Novikov, 2020-04-17 16:37:42

How to call the desired overridden method using polyformism?

I am trying in various ways to bring an instance of class A3 to A2 and call the implementation of the method from A2. The implementation of the method from A3 is always called. What am I doing wrong?

package advanced_classes

fun main(args:Array<String>){
    val a = A3()
    a.method()

    //1
    (a as? A2)?.method()

    //2
    if(a is A2){
        a.method()
    }

}

open class A1{
    open fun method():Unit{
        println("Method from A1")
    }
}

open class A2:A1(){
    override fun method():Unit{
        println("Method from A2")
    }
}

open class A3:A2(){
    override fun method():Unit{
        println("Method from A3")
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
koperagen, 2020-04-17
@Igor-Novikov

Briefly: In the framework of polymorphism, your task is solved by creating a new object, A2.
Explanation: If you define a method in the parent class and then override it in the child, the method of the actual class of the object will always be called, i.e. class whose constructor was called when the object was created. The method called will not depend on the type of reference to this object. Due to this, in fact, polymorphism is achieved: You do not need to know which implementation of the method of the object that was passed to you, and in general the real class of the object. You declare a reference to an interface/abstract class/public class as a parameter to your function/constructor of your class, and work with the methods available to that reference to do what your function/class is intended to do. Thereby giving the chance to the client to vary behavior of your code.
Type casting gives access to class-specific fields, i.e. if there were some other method in A2 (not the implementation of the parent method, but something of your own), after the cast you could call it. But this, again, is not about polymorphism.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question