Interfaces define a contract to which different classes can follow. To do that they must override each function and property defined in the interface.
We first declare Buildable interface, which says whatever class conforms to me must declare:
1) val timeRequired of type Int
2) function build
1 2 3 4 |
interface Buildable { val timeRequired: Int fun build() } |
Interfaces cannot have state. Thus, the properties you declare in your interface cannot be initialized.
Classes that conform to these interfaces must declare and initialize this themselves.
1 2 3 |
class Car (val color: String): Drivable, Buildable { override val timeRequired = 10 // initialize the properties in the classes that conform to the interface } |
Besides declaring a Car type like so:
1 |
val myCar: Car = Car("Red") |
We can also have type of interface Buildable:
1 |
val car:Buildable = Car("Red") |
Which then we can only access the function build, and property timeRequired, as specified in the interface. If class Car conformed to other interfaces, we cannot access the functions of the other interfaces because our type is only for Buildable.
Say we a Truck class that also conforms to Buildable. Thus, we can simply have a reference of type Buildable, and call build on the objects like so
1 2 3 4 5 6 7 |
var vehicle: Buildable = null vehicle = Car("Red") vehicle.build() vehicle = Truck("yellow") vehicle.build() |
Now we are free to change the implementation of function build in class Car and Truck, without affecting this outer code, which does the building. In other words…we can freely change HOW the vehicle is built, without affecting the building of it.