Left Index

Kotlin Abstract Class

An abstract class is a class that cannot be instantiated. We create abstract classes to provide a common template for other classes to extend and use. The members (properties and methods) of an abstract class are non-abstract unless you explicitly use abstract keyword to make them abstract. Let's take an example

Example:
abstract class Animal {
	var color: String
	var maxAge: Int

	constructor(color: String, maxAge: Int) {
		this.color = color
		this.maxAge = maxAge
	}

	abstract fun sound()
}

class Dog : Animal {
	constructor(color: String, maxAge: Int) : super(color, maxAge) {

	}

	override fun sound() {
		println("Dogs barks")
	}
}

In above example we create a class Animal as abstract and we can not create it's object. The class has a non-abstract property color and maxAge and an abstract method sound(). If you need to override these members in the subclass, they should be marked with open keyword.

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var dog = Dog("Black", 10)
	println("Dog color: ${dog.color}, max age of dog: ${dog.maxAge}")
	dog.sound()
}
Output:
Dog color: Black, max age of dog: 10
Dogs barks