Interface

4 0 0
                                        

interface - It is like an abstract class that has an abstract method and and properties. It can also have some method with implementations but it cannot store something on its properties. Its properties is required to be abstract or you need to specify either the get or the set method or both.

syntax:

interface Name{

    val property1: String

   val property2: String

               get() = "Your String value"

    fun yourMethod()

    fun yourMethodWithBody(){

        //statements;

    }

}

Note: 

1. You cannot use the keyword field in the get and set within the interface. 

2. Property1 is implicitly abstract.

Syntax during extending:

class A: Name{

     override val property1: String = "Hello World";

     fun yourMethod(){

         println(property1);

     }

}

Note: 

1. You are only required to override those that are abstract property or method.

2. You can extend one or more interface.

3. Use the keyword super followed by angled brackets with the name of the interface inside to be more specific in case there are conflicts with naming of properties or methods. super<Name>


===================

fun main(){

    val book1 = BookClass("Slime", "slimy")

    book1.dummyMessage()

    book1.displayBookInfo()

}

class BookClass(private val bookTitle: String, private val bookAuthor: String): BookInterface{

    override val title: String

              get() = bookTitle

    override val author: String

              get() = bookAuthor

    fun displayBookInfo(){

        println("Book: $title")

        println("Author: $author")

    }  

}

interface BookInterface{

    val title: String

    val author: String

    val dummy: String

             get() = "BookInterface"

    fun displayBookInfo()

    fun dummyMessage(){

        println("This is the interface $dummy" )

    }

}

===================

Result:

This is the interface BookInterface

Book: Slime

Author: slimy

Kotlin ProgrammingWhere stories live. Discover now