Friday, July 14, 2017

Kotlin OOP: Inheritance

Welcome to kotlin Series

Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding

This is the third post about Kotlin OOP. In this post, we are going to cover Kotlin Inheritance.
Let's start-
First, create a class named Math. This class contains two function name add and sub.

add method -> take two integers and return the addition result of that two integers.
sub method -> also take two integers and return the subtracted result of two integers.

Full math class code-
class Math {

  fun add(a:Int, b:Int):Int{
  return a+b
  }

  fun sub(a:Int, b:Int):Int{
  return a-b
  }
}
Now we create a new class and the class name is Math2. see the code-
class Math2 {

  fun mul(a:Int, b:Int):Int{
  return a*b
  }

  fun div(a:Int, b:Int):Int{return a/b}
}
Now we inherited Math class to Math2. But you get some error. Because by default all the class is final. So you can not modify the class. So that we need to modify the Math class and open keyword before class Math
open class Math {
//some code
}
Now the error will be solved. See the code-
class Math2 : Math(){

  fun mul(a:Int, b:Int):Int{
  return a*b
  }

  fun div(a:Int, b:Int):Int{return a/b}
}
Now in the main method- create a math instance and print use those the two method-
val math = Math()
println("add: ${math.add(20,21)}")
println("add: ${math.sub(22,21)}")
output-
add: 41
add: 1
so we see that we can an easily use add and sub-methods. Now we create the Math2 instance. Through this instance, we can use 4 methods. two class method and Math class method.
Let see-
val math2 = Math2()
println("add: ${math2.add(20,21)}")
println("sub: ${math2.sub(22,21)}")

println("mul: ${math2.mul(20,21)}")
println("div: ${math2.div(22,21)}")
see we use both Math and Math2 class methods.
Output-
add: 41
sub: 1
mul: 420
div: 1
Full main method-
fun main(args: Array<String>){

  val math = Math()
  println("add: ${math.add(20,21)}")
  println("add: ${math.sub(22,21)}")

  val math2 = Math2()
  println("add: ${math2.add(20,21)}")
  println("sub: ${math2.sub(22,21)}")

  println("mul: ${math2.mul(20,21)}")
  println("div: ${math2.div(22,21)}")

}
Output:
add: 41
add: 1
add: 41
sub: 1
mul: 420
div: 1

That's all. In this post, we learn about Kotlin inheritance. In Android app development we use this concept a lot.

Thanks for reading this post.

Happy coding.

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :