Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Inheritance


Sure, I'd be happy to explain Kotlin inheritance in simple terms with an example!

Inheritance is a fundamental concept in object-oriented programming that allows a new class to inherit properties and behaviors (methods) from an existing class. In Kotlin, you can use the colon (:) to indicate that one class inherits from another.

Let's say we have a class called Animal:

Example

open class Animal {
open fun makeSound() {
println("The animal makes a sound")
}
}

Now, let's create a subclass called Dog that inherits from Animal:

Example

class Dog : Animal() {
override fun makeSound() {
println("The dog barks")
}
}

Here's what's happening:

Let's create instances of Animal and Dog and see how inheritance works:

Example

fun main() {
val animal = Animal()
val dog = Dog()

animal.makeSound() // Output: The animal makes a sound
dog.makeSound() // Output: The dog barks
}

As you can see, even though Dog inherits from Animal, it has its own implementation of the makeSound() method. This is the essence of inheritance in Kotlin: reusing code and extending functionality.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java