Abstract class and interface keyword in Kotlin(Chapter-13)

Posted by manasvisawant45 on June 16, 2021 2:55 am


We have studied about abstract class and interface in other languages. These are the common features of Object Oriented programming language, Now let us see what abstract class says in kotlin.

abstract class Fruits {  
var x = 0  
    abstract fun taste()  
}  

The above is a simple syntax of abstract class in kotlin. Abstract classes are partially defined classes, methods, and properties which has no implementation but must be defined into their derived classes. If the derived class does not define or implement the methods of their parent class, then it is also recognized as abstract class. Abstract class or abstract method are open by default(allows inheritance) as well as abstract methods can be overridden or defined by the child classes using the override keyword as defined in an earlier post.

Now let us see interface keyword and how it works in kotlin.

Interface:-In Kotlin, interface works just like in java. They can contain method defination or implementation and as well as abstract methods declaration. An interface can be implemented by its child class or classes without using “implements” keyword for defining its abstract declared methods in interface. The multiple interface can be written in following manner.

class multiExample: First, Second   // example to implement multiple interfaces

The keyword “interface” is used to define an interface in Kotlin also just like in Java. lets us visit a full simple example of interface here.

interface First {
   fun firstmethod() {
      println(" first ")
   }
}
interface Second {
   fun secondMethod() {
      println(" second ")
   }
}

// implements two interfaces
class multiExample: First, Second

fun main(args: Array<String>) {
   val objex = multiExample()
   objex.firstMethod()
   objex.secondMethod()
}

Above is a simple example of interface , which tends to be quite similar to how we use in Java, but the only fact which makes it different in kotlin is that, it does not uses implements keyword while using the interfaces as it base.(or parent).

Feel free to read the post and comment below.

Below is my android application, and is useful for people who has Google Opinion Rewards to cash out. https://play.google.com/store/apps/details?id=com.manasvi.sawant.rewardtocash

If you wanted to create a website, please visit my Fiverr gig link below or contact me at support@techoceanhub.com. https://www.fiverr.com/share/EdZ9L7