Kotlin / Object-Oriented Programming in Kotlin
Exploring Inheritance and Polymorphism
This tutorial delves into the concepts of inheritance and polymorphism in Kotlin. You will understand how to use inheritance to derive new classes and how to use polymorphism to c…
Section overview
5 resourcesCovers OOP concepts like classes, objects, inheritance, and polymorphism.
Exploring Inheritance and Polymorphism in Kotlin
1. Introduction
In this tutorial, we will delve into the concepts of inheritance and polymorphism in Kotlin. The goal is to understand how to use inheritance to derive new classes from existing ones and how to use polymorphism to create flexible code structures.
By the end of this tutorial, you will learn:
- What inheritance and polymorphism are
- How to use inheritance to create derived classes
- How to apply polymorphism in Kotlin
Prerequisites:
- Basic knowledge of Kotlin syntax
- Understanding of classes and objects in Kotlin
2. Step-by-Step Guide
In Kotlin, inheritance is a mechanism where you can derive a class from another class for a hierarchy of classes that share a set of attributes and methods. The class which inherits the properties of another class is called the derived class, and the class whose properties are inherited is called the base class.
Polymorphism is a concept by which we can perform a single action in different ways. So in Kotlin, you can define a method in a class and have a same named method in its child class. This is known as method overriding, or runtime polymorphism.
Best Practices and Tips:
- Make sure to use the
openkeyword to allow a class to be inheritable. - Use the
overridekeyword when overriding a method in a derived class.
3. Code Examples
Example 1: Basic Class Inheritance in Kotlin
// A 'open' class animal
open class Animal {
open fun sound() {
println("The animal makes a sound")
}
}
// A class 'Dog' derived from 'Animal' class
class Dog : Animal() {
override fun sound() {
println("The dog barks")
}
}
fun main(args: Array<String>) {
val myDog: Animal = Dog()
myDog.sound()
}
In this example, Dog is a derived class that inherits from the Animal base class. The sound method in Dog overrides the sound method in Animal.
Expected output:
The dog barks
Example 2: Polymorphism in Kotlin
open class Animal {
open fun sound() {
println("The animal makes a sound")
}
}
class Dog : Animal() {
override fun sound() {
println("The dog barks")
}
}
class Cat : Animal() {
override fun sound() {
println("The cat meows")
}
}
fun main(args: Array<String>) {
val myDog: Animal = Dog()
val myCat: Animal = Cat()
myDog.sound()
myCat.sound()
}
In this example, both Dog and Cat classes override the sound method in their own way, exhibiting polymorphism.
Expected output:
The dog barks
The cat meows
4. Summary
In this tutorial, we covered the concepts of inheritance and polymorphism in Kotlin. We learned how to use inheritance to derive new classes and how to use polymorphism to create flexible code structures.
Next, you can explore other object-oriented concepts in Kotlin, like abstraction and encapsulation.
Additional resources:
- Kotlin Documentation
- Kotlin for Java Developers (Coursera)
5. Practice Exercises
Exercise 1: Create a base class Shape with a method area(). Derive two classes Rectangle and Circle from Shape and override the area() method.
Exercise 2: Implement polymorphism by creating an array of Shape objects and calling the area() method.
Solutions:
// Solution for Exercise 1
open class Shape {
open fun area() {
println("Area of shape")
}
}
class Rectangle(var width: Int, var height: Int) : Shape() {
override fun area() {
println("Area of rectangle is ${width * height}")
}
}
class Circle(var radius: Int) : Shape() {
override fun area() {
println("Area of circle is ${3.14 * radius * radius}")
}
}
// Solution for Exercise 2
fun main(args: Array<String>) {
val myShapes: Array<Shape> = arrayOf(Rectangle(4,5), Circle(3))
for(shape in myShapes) {
shape.area()
}
}
In the first exercise, Rectangle and Circle classes are derived from Shape and override the area() method. In the second exercise, an array of Shape objects is created and area() method is called for each object, demonstrating polymorphism.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article