Kotlin Inheritance

18. Kotlin Inheritance 18.1 Inheritance 18.2 Kotlin open keyword 18.3 Inheriting methods from a class 18.4 Method Overriding


Inheritance

Inheritance is the process in which one or more child class is derived from the parent class. It allows us to reuse, extend the properties and methods of the existing class. By using this, we can reuse the properties and methods of the base class in a derived class.

Kotlin open keyword

Before exploring the inheritance example, let's understand the use of open keyword.

In other programming language like java, maybe you learn about the keyword final. The final keyword prevents the child classes from overriding the properties and methods of a parent class. In Kotlin, by default, all the classes are final, means they cannot be inherited from. The open keyword is used to allow inheritance of a class.

This is the given example to define a base class.

open class animal{  
	var legs = 'four'
}

This is the given example to define a derived class.

open class animal{  
	fun pet(){
		println("Live at home")
	}
}
class dog:animal(){
	
}
fun main(args : Array<String>)  { 
	var obj1=dog()
	obj1.pet()
}
Output
Live at home

In the above example, the derived class dog inherits the properties and methods of the base class animal. The colon(:) operator is used for inheritance.



Inheriting methods from a class

The given example explained how we can access methods of both base class and derived class.

open class animal{  
	fun pet(){
		println("Live at home");
	}
}
class dog:animal(){
	fun food(){
		println("Dog eat non vegitarian");
	}
}
fun main(args : Array<String>)  { 
	var obj1=dog()
	obj1.pet()
	obj1.food()
}

In the above example, we have instantiated the derived class and accessed methods of both base class and derived class.


Method Overriding

Method overriding is used to override the properties and methods of the base class in the derived class of the same type, but with different behavior.

open class animal{  
	fun pet(){
		println("kept primarily for protection, entertainment");
	}
}
class dog:animal(){
	override fun pet(){
		println("Dog are domesticated mammals.");
	}
}
fun main(args : Array<String>)  {  
	var obj1=dog()
	obj1.pet()
}
Output
Live at home
Dog eat non vegitarian






Read more articles


General Knowledge



Learn Popular Language