Tuesday 23 January 2018

Kotlin: Abstract classes

An abstract class can have methods without implementation. Abstract class is defined using ‘abstract’ keyword.

Ex
interface Arithmetic{
 fun sum(x : Int, y : Int) : Int
 fun sub(x : Int, y : Int) : Int
 fun mul(x : Int, y : Int) : Int
 fun div(x : Int, y : Int) : Int
}

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
}

You can’t define instance (object) to abstract class.

Abstract method
Just like how you defined abstract class, you can define abstract method (method without implementation) using the keyword ‘abstract’.

abstract class ArithmeticImpl : Arithmetic{
 override fun sum(x : Int, y : Int) : Int{
  return x + y
 }
 
 override fun sub(x : Int, y : Int) : Int{
  return x - y
 }
 
 abstract fun areaofCircle(radius : Int) : Int
}

In the above snippet, I declared ‘areaOfCircle’ as abstract method. Any concrete class that is extending this abstract class must provide implementation to all the abstract methods.


class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

Find the below working application.


HelloWorld.kt

interface Arithmetic {
 fun sum(x: Int, y: Int): Int
 fun sub(x: Int, y: Int): Int
 fun mul(x: Int, y: Int): Int
 fun div(x: Int, y: Int): Int
}

abstract class ArithmeticImpl : Arithmetic {
 override fun sum(x: Int, y: Int): Int {
  return x + y
 }

 override fun sub(x: Int, y: Int): Int {
  return x - y
 }

 abstract fun areaofCircle(radius: Int): Double
}

class ConcreteArithmetic : ArithmeticImpl() {
 override fun mul(x: Int, y: Int): Int {
  return x * y
 }

 override fun div(x: Int, y: Int): Int {
  return x / y
 }

 override fun areaofCircle(radius: Int): Double {
  return 3.14 * radius * radius
 }
}

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

 var sumOf10And20 = obj.sum(10, 20)
 var subOf10And20 = obj.sub(10, 20)
 var mulOf10And20 = obj.mul(10, 20)
 var divOf10And20 = obj.div(10, 20)
 var areaOfCircle = obj.areaofCircle(5)

 println("sumOf10And20 = $sumOf10And20")
 println("subOf10And20 = $subOf10And20")
 println("mulOf10And20 = $mulOf10And20")
 println("divOf10And20 = $divOf10And20")
 println("areaOfCircle = $areaOfCircle")

}


Output

sumOf10And20 = 30
subOf10And20 = -10
mulOf10And20 = 200
divOf10And20 = 0
areaOfCircle = 78.5






Previous                                                 Next                                                 Home

No comments:

Post a Comment