Saturday 6 January 2018

Kotlin: Overriding methods

By using ‘override’ keyword, you can override the methods of base class. By default all the methods in a class are final (not overridable), you can make them overridable by using ‘open’ keyword’.

Override.kt
open class BaseClass{
 open fun sayHello(){
  println("******Hello World******")
 }
}

class DerivedClass : BaseClass(){
 override fun sayHello(){
  println("@@@@Hello World@@@@@")
 }
}
fun main(args: Array<String>) {
 var obj = DerivedClass()
 
 obj.sayHello()
 
}


Output
@@@@Hello World@@@@@


As you observe above snippet, DerivedClass inhrites from BaseClass. sayHello() method of DerivedClass override the sayHello() method of BaseClass using override keyword.

A method defined with the keyword ‘override’ is itself open, so the child classes of the DerivedClass, can override this method.


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

Output
####Hello World####

If you want to prohibit the re-overriding, use the keyword final.

Ex
open class DerivedClass : BaseClass() {
         final override fun sayHello() {
                 println("@@@@Hello World@@@@@")
         }
}


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 final override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

When you try to compile above program, kotlin compiler throws below error.

'sayHello' in 'DerivedClass' is final and cannot be overridden





Previous                                                 Next                                                 Home

No comments:

Post a Comment