Kotlin program | Example of inheritance

Kotlin | Inheritance: Here, we are implementing a Kotlin program to demonstrate the example of inheritance.
Submitted by IncludeHelp, on June 03, 2020

Inheritance

  • Inheritance is a mechanism wherein a new class is derived from an existing class.
  • All Kotlin Classes have a common Superclass 'Any', it is the Default Superclass with no Super Type declared.
    class Student  // implicitly inherits from Any
    
  • 'Any' Class has three methods
    1. equals()
    2. hashCode()
    3. toString()
    These methods available for all Kotlin class implicitly.
  • By Default All class is Final in Kotlin, They can't be inherited.
  • Use 'open' keyword, to make class inheritable,
    open class <class name>  // make class inheritable
    
  • To declare explicit supertype, placer base class name after colon into the class header.
    open class Base{}
    class Derived : Base{}
    

Program for Inheritance in Kotlin

package com.includehelp

//Declare class, use 'open' keyword 
//to make class inheritable
//Class without declare primary constructor
open class Company{
    //member function
    fun getCompany(){
        println("Base Methods : Company Info")
    }
}
//Declare class using inheritance
class Department : Company() {
    //member function
    fun getDept(){
        println("Derived Method :  Dept Info")
    }
}

//Declare class, use 'open' keyword 
//to make class inheritable
open class Shape(val a:Int){
    fun getBaseValue(){
        println("Base value : $a")
    }
}
//if derived class has primary constructor 
//then base class can initialized there
//using primary constructor parameters
class Circle(val b:Int): Shape(b) {
    fun getChildValue(){
        println("Child value : $b")
    }
}


//Main Function, Entry point of program
fun main(args:Array<String>){

    //create derived class object
    val company = Department()
    //access base class function
    company.getCompany()
    //access derived class function
    company.getDept()


    //create derived class object and passed parameter
    val shape = Circle(20)
    //access base class function
    shape.getBaseValue()
    //access derived class function
    shape.getChildValue()
}

Output:

Base Methods : Company Info
Derived Method :  Dept Info
Base value : 20
Child value : 20


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.