Kotlin: Inheritance - TechwithRiya
You are here
Home > Kotlin > Kotlin: Inheritance

Kotlin: Inheritance

Inheritance

In this post we will discuss Inheritance in kotlin with example.

  • Inheritance provides the reusability of the previously defined functions. The previously defined class is called super(base, parent) class and the class that inherits the super class called the sub(derived, child) class.
  • A derived class implicitly get all the parent class fields.
  • All classes in Kotlin have a common superclass Any, that is a default super for a class with no super types declared.
  • In kotlin by default class is consider final so for inheriting use open open keyword indicates that class can be inherited from. open is exactly opposite of final.
  • For inheritance use :base_classname() is used.
  • Multiple inheritance is not supported in kotlin.

Example:

open class classbase(){
fun add(a:Int,b:Int):Int
{
return a+b;
}
fun sub(a:Int,b:Int):Int
{
return a-b;
}

}
class classderived():classbase()
{
fun mul(a:Int,b:Int):Int
{
return a*b;
}
fun div(a:Int,b:Int):Int
{
return a/b;
}
}
fun main(args:Array<String>)
{
var ob1=classderived();
var sum=ob1.add(2,4);
println(“sum=”+sum);
var sub=ob1.sub(2,4);
println(“sub=”+sub);
var mul=ob1.mul(2,4);
println(“Mul=”+mul);
var div=ob1.div(2,4);
println(“Div=”+div);
}
output:

Explanation:
In above example, we create a super class classbase it contains two functions sum and sub. And subclass classderived it contains mul and div function and this class extends the classbase. In function main, we create an object of classdederived and call all functions.

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