The inheritance in Kotlin language is almost the same as Java with a slight modification. Here is the general systax of Kotlin inheritance in a simple example:
// Base parent (Super class)
open class Person {
}
// Childe class (Sub class)
class Students: Person() {
}
Here is an example with constructor:
open class Person(val name:String,val age:Int){
}
//Inheritance for Employee from Person class
class Employee(name:String,age:Int, val salary:Int):Person(name,age){
}
Here is the complete code with intanciation :
open class Person(val name:String,val age:Int){
}
//Inheritance for Employee from Person class
class Employee(name:String,age:Int, val salary:Int):Person(name,age){
}
fun main(args: Array< String >) {
//Create object Person P
var E=Employee("Richard",35,28000)
println("Empoyee name is : " + E.name)
println("The Employee's age is : " + E.age)
println("The Employee's salary is : " + E.salary)
}
Inheritance from the methods of the super class.
Here's an example of a child class: Rectangle that inherits the perimeter method from the super class Parallelogram:
open class Parallelogram(val side1:Int,val side2:Int){
fun perimeter():Int{
return 2*(this.side1+this.side2)
}
}
//Inheritance for Employee from Person class
class Rectangle(side1:Int,side2:Int):Parallelogram(side1,side2){
}
fun main(args: Array< String >) {
//Create object Rectangle
var R=Rectangle(10,7)
println("The perimeter of rectangle R is : " + R.perimeter())
}
Younes Derfoufi