Abstract classes in Kotlin

In this article, we are going to learn about abstract classes. Here you will find what abstract class is and how they can be implemented in Kotlin?
Submitted by Aman Gautam, on December 28, 2017

Abstract class is a class which is designed to provide a base for the class to which it is inherited. It cannot be instantiated but only can be sub classed or inherited. Abstract class may or may not contain any abstract method. It can also have constructor, normal methods or any normal variable. They all are used in the class in which they are inherited by creating the object of the derived class.

Abstract methods are defined using abstract keyword and they do not contain any code and declared without implementation. They are further implemented in subclasses.

abstract fun showprofile()    // abstract method

In Kotlin, we can create abstract class using abstract keyword as follows

abstract class Student(name:String, std :Int){
  abstract fun showprofile()
}

Here is a program for abstract class in Kotlin

abstract class School(var name: String, std: Int) {
    var school = "ABC School"
    fun name(): String {
        return name;
    }

    abstract fun showprofile()
}

class Student(name: String, var std: Int) : School(name, std) {
    override fun showprofile() {
        println(" School : $school\n Name : $name, Class : $std")
    }
}

fun main(Args: Array<String>) {
    var obj = Student("Krishna", 4)
    println(" Calling Abstract method")
    obj.showprofile()
    println("\n calling non abstract method")
    println(" Name : ${obj.name()}")
}

In this program, we have created an abstract class school which contains one abstract method showprofile() and one non abstract method name(). Class student is inheriting the school class and implementing its showprofile() method . The values name and std are passed to the constructor of school class. In the main function we have creates an object of Student class and through which we have called showprofile() function and name() function.

Read more: Interfaces in Kotlin.




Comments and Discussions!

Load comments ↻





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