Inheritance and function overriding in Kotlin

In the previous article we introduced object oriented programming(OOP) in Kotlin with class and objects, now in this article we will discuss about an important feature of OOP i.e. inheritance and function overriding.
Submitted by Aman Gautam, on December 11, 2017

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).

open class vehicle{
    var price:Int=0
}

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

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

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.

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
    }
}

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.

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.