You are here
Home > Kotlin

Kotlin: Interfaces

Interfaces in kotlin

Interfaces

In this post we will discuss Interfaces in kotlin, use of it, and how to declare interface in kotlin.

  • Interface only have function declaration it not contains its implementation. In kotlin interface is by default open.
  • You have to use override keyword in class to implement its function.
  • If you implement interface and not override its function, then you have to provide the default implementation of the function with its declaration.

Example:
interface op
{
fun sum(n1:Int,n2:Int)
fun mul(n1:Int,n2:Int) {println(“Mul=”+(n1*n2));}
}
class M():op
{
override fun sum(n1: Int, n2: Int) {
println(“Sum=”+(n1+n2));
}
override fun mul(n1: Int, n2: Int) {
println(“Mul=”+(n1*n2*10));
}
}
class N():op
{
override fun sum(n1: Int, n2: Int) {
println(“Sum=”+(n1+n2+10));
}
}
fun main(args:Array<String>)
{
var m=M();
m.sum(2,2);
m.mul(2,2);
var n=N();
n.sum(2,2);
n.mul(2,2);

}
output:

Explanation:
In above example, we create an interface op that has two function sum and mul and mul have default implementation of the function. We create two class M and N, M has both function implementation and N has only sum function implementation.
You can also by SQL 70-761 book write by me fromĀ Amazon.
You can also by Kotlin Book write by me fromĀ Amazon.

Microsoft SQL 70-762 Practice Test.

Microsoft MCSA 70-761 Practice Test:

Leave a Reply

Top