In Kotlin, it is possible to inherit class properties and functions from one class to another. We group the "inheritance concept" into two categories:
- subclass [child] - the class that inherits from another class
- superclass [parent] - the class being inherited from
In the example below, MyChildClass
[subclass] inherits the properties from the MyParentClass
class [superclass]:
Example
// Superclass
open class MyParentClass {
val x = 5
}
// Subclass
class MyChildClass: MyParentClass[] {
fun myFunction[] {
println[x] // x is now inherited from the superclass
}
}
// Create an object of MyChildClass and call myFunction
fun main[] {
val myObj = MyChildClass[]
myObj.myFunction[]
}
Try it Yourself »Example Explained
Use the open
keyword in front of the superclass/parent, to make this the class other classes should inherit properties and functions from.
To inherit from a class, specify the name of the subclass, followed by a colon :
, and then the name of the superclass.
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse properties and functions of an existing class when you create a new class.
In my previous article I talked about how Kotlin saves us writing boilerplate codes the one we have to write in Java and there I gave an example of a simple class showing the differences in class structures in both languages. Now let’s know more facts about Kotlin classes and functions in this article.
How to declare a classIf you want to declare a class, you just need to use the keyword class:
class MainActivity { }
Classes have a unique default constructor. We’ll see that we can create extra constructors for some exceptional cases, but keep in mind that most situations only require a single constructor.
If the class has no body, curly braces can be omitted.
class Empty
Parameters are written just after the name. Brackets are not required if the class doesn’t have any content:
class Person[name: String, surname: String]
ConstructorsA class in Kotlin can have a primary constructor and one or more secondary constructors.
The primary constructor
The primary constructor is part of the class header: it goes after the class name [and optional type parameters].
class Person constructor[firstName: String] {
}
If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted:
class Person[firstName: String] {
}
But if the constructor has annotations or visibility modifiers, the constructor keyword is required, and the modifiers go before it:
class Customer public @Inject constructor[name: String] { ... }
For more details, see .
The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks, which are prefixed with the init keyword.
During an instance initialization, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers:
class InitOrderDemo[name: String] {val firstProperty = "First property: $name".also[::println]init {println["First initializer block that prints ${name}"]}val secondProperty = "Second property:${name.length}".also[::println]init {println["Second initializer block that prints ${name.length}"]}}
Note that parameters of the primary constructor can be used in the initializer blocks. They can also be used in property initializers declared in the class body:
class Customer[name: String] {
val customerKey = name.toUpperCase[]
}
In fact, for declaring properties and initializing them from the primary constructor, Kotlin has a concise syntax:
class Person[val name: String, val surname: String] {
// ...
}
For example the code above is equivalent to the code shown below in Java:
public class Person{private String name;private String surname;
public String getName[] {return name;}public void setName[String name] {this.name = name;}
public String getSurname[] {return surname;}public void setSurname[String surname] {this.name = surname;}
You can access these properties [fields in kotlin are called properties] just using the names
class Empty
0Secondary Constructor
The class can also declare secondary constructors, which are prefixed with constructor:
class Empty
1If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor[s]. Delegation to another constructor of the same class is done using the this keyword:
class Empty
2Note that code in initializer blocks effectively becomes part of the primary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body. Even if the class has no primary constructor, the delegation still happens implicitly, and the initializer blocks are still executed:
class Empty
3If a non-abstract class does not declare any constructors [primary or secondary], it will have a generated primary constructor with no arguments. The visibility of the constructor will be public. If you do not want your class to have a public constructor, you need to declare an empty primary constructor with non-default visibility:
class Empty
4Creating instances of classesNOTE: On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.
class Person[name: String, surname: String]
8
To create an instance of a class, we call the constructor as if it were a regular function:
class Empty
5Note that Kotlin does not have a new keyword.
Class InheritanceBy default, a class always extends from Any [similar to Java Object], but we can extend any other classes.
Note:
class Person[name: String, surname: String]
9 is notclass Person constructor[firstName: String] {
0; in particular, it does not have any members other than
}class Person constructor[firstName: String] {
1,
}class Person constructor[firstName: String] {
2 and
}class Person constructor[firstName: String] {
3.
}
Classes are closed by default [final], so we can only extend a class if it’s explicitly declared as open or abstract:
class Empty
6Note that when using the single constructor nomenclature, we need to specify the parameters we’re using for the parent constructor. That’s equivalent to calling super[] in Java.
If the class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword, or to delegate to another constructor which does that. Note that in this case different secondary constructors can call different constructors of the base type:
class Empty
7Overriding Methods
Unlike Java, Kotlin requires explicit annotations for overridable members [we call them open] and for overrides:
class Empty
8The override annotation is required for
class Person constructor[firstName: String] {
}
4. If it were missing, the compiler would complain. If there is no open annotation on a function, like class Person constructor[firstName: String] {
}
5, declaring a method with the same signature in a subclass is illegal, either with override or without it. In a final class [e.g. a class with no open annotation], open members are prohibited.A member marked override is itself open, i.e. it may be overridden in subclasses. If you want to prohibit re-overriding, use final:
class Empty
9Overriding Properties
Overriding properties works in a similar way to overriding methods; properties declared on a superclass that are then redeclared on a derived class must be prefaced with override, and they must have a compatible type. Each declared property can be overridden by a property with an initializer or by a property with a getter method.
class Person[name: String, surname: String]
0You can also override a
class Person constructor[firstName: String] {
}
6 property with a class Person constructor[firstName: String] {
}
7 property, but not vice versa. This is allowed because a class Person constructor[firstName: String] {
}
6 property essentially declares a getter method, and overriding it as a class Person constructor[firstName: String] {
}
7 additionally declares a setter method in the derived class.Note that you can use the override keyword as part of the property declaration in a primary constructor.
class Person[name: String, surname: String]
1Derived class initialization order
During construction of a new instance of a derived class, the base class initialization is done as the first step [preceded only by evaluation of the arguments for the base class constructor] and thus happens before the initialization logic of the derived class is run.
class Person[name: String, surname: String]
2Output:
class Person[name: String, surname: String]
3It means that, by the time of the base class constructor execution, the properties declared or overridden in the derived class are not yet initialized. If any of those properties are used in the base class initialization logic [either directly or indirectly, through another overridden open member implementation], it may lead to incorrect behavior or a runtime failure. Designing a base class, you should therefore avoid using openmembers in the constructors, property initializers, and init blocks.
Calling the superclass implementation
Code in a derived class can call its superclass functions and property accessors implementations using the super keyword:
class Person[name: String, surname: String]
4Inside an inner class, accessing the superclass of the outer class is done with the super keyword qualified with the outer class name:
class Person[firstName: String] {
}
0: class Person[name: String, surname: String]
5Overriding Rules
In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits many implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation [perhaps, using one of the inherited ones]. To denote the supertype from which the inherited implementation is taken, we use super qualified by the supertype name in angle brackets, e.g.
class Person[firstName: String] {
}
1: class Person[name: String, surname: String]
6It’s fine to inherit from both
class Person[firstName: String] {
}
2 and class Person[firstName: String] {
}
3, and we have no problems with class Person[firstName: String] {
}
4 and class Person[firstName: String] {
}
5 since class Person[firstName: String] {
}
6 inherits only one implementation of each of these functions. But for class Person[firstName: String] {
}
7 we have two implementations inherited by class Person[firstName: String] {
}
6, and thus we have to override class Person[firstName: String] {
}
7 in class Person[firstName: String] {
}
6 and provide our own implementation that eliminates the ambiguity.Abstract Classes
A class and some of its members may be declared abstract. An abstract member does not have an implementation in its class. Note that we do not need to annotate an abstract class or function with open — it goes without saying.
We can override a non-abstract open member with an abstract one
class Person[name: String, surname: String]
7This covered most of the concepts related to Classes and Inheritance in Kotlin. For more details visit Kotlin documentation.