Inheritance and function overriding in Kotlin

By IncludeHelp Last updated : December 04, 2024

Kotlin Inheritance

Inheritance is one of the major aspect of OOP. It allow us to define a class and that can be inherited in multiple forms, like real world, features of parent class are accessible to child class through inheritance. It helps in designing larger application easily and efficiently.

The class from which child class inheritsall or some properties is known as Base class and the class which inherits properties from base class is known as derived class. Derived class contains feature from base class as well as its own feature.

In kotlin, to make any class inheritable we have to make it open. By default, all classes are final (final in java).

Syntax

open class vehicle{
  var price:Int=0
}

Now to inherit a class we use : (colon) symbol.

class car : vehicle(){
  var name:String=""
}

Kotlin Class Initialization with Base Types

If class has primary constructor, then base type must be initialized by using parameters of primary constructor. If no, then secondary class has to initialize the base type using super keyword.

Example

open class vehicle{
  var price:Int=0
  constructor(price: Int){
    this.price=price
  }

}
class car : vehicle
{   var name:String=""
  constructor(name:String,price: Int):super(price){
    this.name=name
  }
}

Kotlin Overriding Member Functions

In inheritance where base class and derived class have same function declaration but different definitionFunctionthen this is known as function overriding.

To override a method, make the function open in base class and addprefix override before function definition in derived class.

Example

open class vehicle
{
  open fun display(){
    print("Class vehicle")
  }
}
class car : vehicle()
{   
  override fun display(){
    print("Class car")
  }
}

So on calling display() function ,

var ob=car1()
ob.display()

Output

Class car

Kotlin - Inheritance Example

open class vehicle{
  var price:Int=0
  constructor(price: Int){
    this.price=price
  }

}
class car : vehicle
{   var name:String=""
  constructor(name:String,price: Int):super(price){
    this.name=name
  }
}

fun main(arr:Array<String>){
  var ob=car("HYUNDAI",500000);

  println("Name : ${ob.name}")
  println("price : ${ob.price}")
}

Output

Name : HYUNDAI
price : 500000

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.