Home » Kotlin

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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.