Kotlin Inheritance
In Kotlin, you can create a class that inherits from another class using the :
symbol followed by the name of the base class. The subclass can access all the properties and methods of the base class, and can also define its own properties and methods.
Here's an example of a class hierarchy with inheritance:
open class Animal(val name: String) { open fun makeSound() { println("$name makes a generic animal sound") } } class Dog(name: String) : Animal(name) { override fun makeSound() { println("$name says woof!") } } class Cat(name: String) : Animal(name) { override fun makeSound() { println("$name says meow!") } }
In this example, we have defined a base class called Animal
with a property name
and a method makeSound()
. We have also defined two subclasses, Dog
and Cat
, that inherit from Animal
and override the makeSound()
method with their own implementations.
To create an instance of a subclass, you can simply call its constructor and pass any required arguments:
val dog = Dog("Fido") val cat = Cat("Whiskers") dog.makeSound() // prints "Fido says woof!" cat.makeSound() // prints "Whiskers says meow!"
In this example, we create instances of the Dog
and Cat
classes and call their makeSound()
methods, which print the appropriate sound to the console.
In Kotlin, you can also create abstract classes and interfaces that can be used to define common behavior for a group of classes. An abstract class is a class that cannot be instantiated and is meant to be subclassed. An interface is a collection of abstract methods that can be implemented by any class.
Here's an example of an abstract class and an interface:
abstract class Shape(val name: String) { abstract fun area(): Double } interface Drawable { fun draw(color: String) } class Circle(name: String, val radius: Double) : Shape(name), Drawable { override fun area(): Double { return Math.PI * radius * radius } override fun draw(color: String) { println("Drawing $name with radius $radius and color $color") } }
In this example, we have defined an abstract class called Shape
with a property name
and an abstract method area()
. We have also defined an interface called Drawable
with a method draw()
. We have then defined a subclass called Circle
that inherits from Shape
and implements Drawable
. The Circle
class overrides the area()
method with its own implementation and provides an implementation of the draw()
method.
To create an instance of the Circle
class, you can call its constructor and pass any required arguments:
val circle = Circle("Circle", 5.0) println(circle.area()) // prints "78.53981633974483" circle.draw("blue") // prints "Drawing Circle with radius 5.0 and color blue"
In this example, we create an instance of the Circle
class and call its area()
method to calculate the area of the circle. We then call its draw()
method to draw the circle with the specified color.