Interfaces and polymorphism

In our previous example, we can see that the car class implements two interfaces—IDriveable and IFlyable.  The tesla class object can run on the road and fly in the sky. 

We can restrict an object to a specific interface, even if a class has implemented more than one interface. Let's say we want to create an instance of a normal class that should not contain the functionalities of a flying object. To achieve this, we need to define the type of the interface that we want to expose. Create an object called Toyota, declare it with the IDriveable interface, and initialize it with Car along with the required parameters:

fun main(args: Array<String>) {
val toyota : IDriveable = Car(4, "Toyota")
toyota.startEngine()
toyota.moveForward()
}

Because the Car class has implemented the IDriveable interface, it is possible to declare one of the interfaces by creating a Car object. This is a very powerful feature. Notice that by opening the IDriveable interface, the class instance can access only the functions that are implemented in the IDriveable interface. If we try to access the fly function from the IFlyable interface, Kotlin will throw a compile-time error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.11.247