Interfaces

An interface is somewhat similar to an abstract class in that it provides a list of functions to implement. An interface is basically a contract between classes in which each class has to provide an implementation of the functions that are defined in the interface. An interface is declared with the interface keyword. Let's take a look at an example:

interface interface_name{  
fun func1()
fun func2()
}

interface IPrintable {
fun print()
}

Creating an interface is similar to creating a class. The names of the interfaces start with the letter I. This is not a syntax requirement, but a common practice to differentiate between classes and interfaces because their syntax is similar:

class Invoice : IPrintable {
override fun print() {
println("Invoice is printed")
}
}

In this example, the Invoice class implements the IPrintable interface and provides an implementation of the print function. The interface is a contract that requires a class to implement certain functions. For example, the invoice class interface must have a function to print the invoice. While creating a button or checkbox class, we can implement the IClickable interface to enforce the button or checkbox class to implement the click function because a button without click functionality is just an image:

interface Clickable{
fun click()
}

class Button : Clickable {
override fun click() {
println("Button is clicked")
}
}
fun main(args: Array<String>) {

var invoice = Invoice()
invoice.print()

var button = Button()
button.click()
}

As we can see, the Button class implements the click function and the invoice class implements the print function. The interface acts as a contract that states that any class that implements it has to guarantee that the function signatures listed in the interface are implemented.

The abstract class can have both abstract and non-abstract functions. Each function mentioned in the interface, however, is necessarily public and abstract by default so there is no need to use the abstract keyword with the function signature.

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

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