Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Inheritance

Kotlin Inheritance

Inheritance lets a subclass reuse the properties and methods of its superclass and change their behavior when needed.

Kotlin's inheritance is more conservative than Java's: classes and methods are final by default and must be explicitly opened to be inherited or overridden.


Any and common methods

All classes in Kotlin share a common supertype, Any; classes without an explicit superclass inherit from it by default.

Any declares three methods: equals(), hashCode(), and toString(), whose default implementations can all be overridden by subclasses.

Example

// File path: Main.kt

class

Site

(

val name

:

String

, val url

:

String

)

{

   

// Override toString to make printed output readable

    override fun toString

(

)

:

String

=

"Site(name=$name, url=$url)"

   

// Override equals to compare by content

    override fun equals

(

other

:

Any

?

)

:

Boolean

{

       

if

(

this

===

other

)

return

true

       

if

(

other

!

is Site

)

return

false

       

return

name

==

other.

name

&&

url

==

other.

url

   

}

   

// After overriding equals you must also override hashCode so equal objects have the same hash code

    override fun hashCode

(

)

:

Int

=

31

name.

hashCode

(

)

url.

hashCode

(

)

}

fun main

(

)

{

    val a

=

Site

(

"RUNOOB"

,

"www.runoob.com"

)

    val b

=

Site

(

"RUNOOB"

,

"www.runoob.com"

)

    println

(

a

)

    println

(

"a == b:${a == b}"

)

                   

// Equal in content

    println

(

"a === b:${a === b}"

)

                 

// Not the same object

    println

(

"Same hash code: ${a.hashCode() == b.hashCode()}"

)

}

Output result:



Site(name=RUNOOB, url=www.runoob.com)

a == b:true

a === b:false

哈希码相同:true

== calls equals() and compares content; === compares references to determine whether it is the same object.

Tip:Overriding equals without hashCode makes objects behave incorrectly in HashSet and HashMap. The two must appear as a pair.


The open keyword

Kotlin classes are final by default and cannot be inherited; to allow inheritance you must add open.

Members inside a class are also final by default; to allow overriding you must add open individually.

Example

// File path: Main.kt

// Only after adding open can it be inherited

open

class

Animal

(

val name

:

String

)

{

   

// Only after adding open can it be overridden

    open fun sound

(

)

:

String

=

"..."

   

// Without open, it is final by default and cannot be overridden by subclasses

    fun eat

(

)

:

String

=

"$name is eating"

}

class

Dog

(

name

:

String

)

:

Animal

(

name

)

{

    override fun sound

(

)

:

String

=

"Woof woof"

}

fun main

(

)

{

    val dog

=

Dog

(

"Wangcai"

)

    println

(

dog.

sound

(

)

)

    println

(

dog.

eat

(

)

)

    println

(

"dog is Animal: ${dog is Animal}"

)

}

Output result:



汪汪

旺财 在吃东西

dog 是 Animal:true

If you write class Cat : Animal("Mimi") and Animal is not open, the compiler will report an error directly.


Base class initialization when the subclass has a primary constructor

When the subclass has a primary constructor, the superclass must be initialized in place in the subclass header, written as the superclass name followed by parentheses.

The superclass's init blocks run before the subclass's init blocks, consistent with most object-oriented languages.

Example

// File path: Main.kt

open

class

Site

(

val name

:

String

)

{

    init

{

        println

(

"Base init: $name"

)

   

}

    open fun show

(

)

:

String

=

"Site: $name"

}

// The subclass primary constructor passes name to the superclass constructor

class

SubSite

(

name

:

String

, val url

:

String

)

:

Site

(

name

)

{

    init

{

        println

(

"Subclass init: $url"

)

   

}

    override fun show

(

)

:

String

=

"${super.show()}, address: $url"

}

fun main

(

)

{

    val s

=

SubSite

(

"RUNOOB"

,

"www.runoob.com"

)

    println

(

s.

show

(

)

)

}

Output result:



基类 init:RUNOOB

子类 init:www.runoob.com

站点:RUNOOB,地址:www.runoob.com

When the subclass constructor runs, the superclass's properties have already been initialized, so super.show() can safely read name.


super calls when the subclass has no primary constructor

When the subclass has no primary constructor, the superclass must be initialized in every secondary constructor with super(...), or delegated to another secondary constructor that already initializes the superclass.

The following example gives the superclass only secondary constructors and the subclass also uses only secondary constructors.

Example

// File path: Main.kt

open

class

Person

{

    open val role

:

String

=

"Ordinary person"

    constructor

(

name

:

String

)

{

        println

(

"Person secondary constructor: $name"

)

   

}

   

// Delegate to the previous secondary constructor to avoid repeated initialization

    constructor

(

name

:

String

, age

:

Int

)

:

this

(

name

)

{

        println

(

"Person secondary constructor (with age): $name, $age"

)

   

}

}

class

Student

:

Person

{

    constructor

(

name

:

String

)

:

super

(

name

)

{

        println

(

"Student secondary constructor: $name"

)

   

}

    constructor

(

name

:

String

, age

:

Int

)

:

super

(

name, age

)

{

        println

(

"Student secondary constructor (with age): $name, $age"

)

   

}

    override val role

:

String

=

"Student"

}

fun main

(

)

{

    val s

=

Student

(

"Xiao Ming"

,

18

)

    println

(

"Role: ${s.role}"

)

}

Output result:



Person 次构造器:小明

Person 次构造器(带年龄):小明,18

Student 次构造器(带年龄):小明,18

角色:学生

Either way, the superclass constructor always finishes before the subclass constructor body begins.


Method overriding with override

To override a superclass member, a subclass must write the override keyword; the compiler checks that the member exists and is open.

An overridden member remains open by default; to prevent further overriding, add final.

Example

// File path: Main.kt

open

class

Base

{

    open fun foo

(

)

:

String

=

"Base.foo"

    open fun bar

(

)

:

String

=

"Base.bar"

}

open

class

Middle

:

Base

(

)

{

   

// After override it is still open by default, so subclasses can override again

    override fun foo

(

)

:

String

=

"Middle.foo"

   

// After adding final, subsequent subclasses cannot override

   

final

override fun bar

(

)

:

String

=

"Middle.bar"

}

class

Leaf

:

Middle

(

)

{

    override fun foo

(

)

:

String

=

"Leaf.foo"

   

// override fun bar(): String = "Leaf.bar" // Compile error: bar is locked by final

}

fun main

(

)

{

    val leaf

=

Leaf

(

)

    println

(

leaf.

foo

(

)

)

    println

(

leaf.

bar

(

)

)

}

Output result:



Leaf.foo

Middle.bar

foo() is overridden again by Leaf, while bar() stops at Middle; that is the effect of final override.


Property overriding

Properties can also be overridden. The rule is: a superclass val property can be overridden by a subclass val or var, but a superclass var cannot be overridden by a val.

The reason is intuitive: val only promises a getter, while var additionally provides a setter; capabilities can only be added, not removed.

Example

// File path: Main.kt

open

class

Site

{

    open val name

:

String

=

"RUNOOB"

   

// Only a getter, no backing field

    open val url

:

String

        get

(

)

=

"www.runoob.com"

}

class

SubSite

(

    override val name

:

String

,    

// Override a val property in the primary constructor

   

private

val rawUrl

:

String

)

:

Site

(

)

{

   

// val can be overridden as var, but not the other way around

    override var url

:

String

=

rawUrl

        get

(

)

=

field

        set

(

value

)

{

            field

=

value

       

}

}

fun main

(

)

{

    val s

=

SubSite

(

"Runoob"

,

"www.runoob.com"

)

    println

(

s.

name

)

    println

(

s.

url

)

   

// Because the subclass overrode it as var, it can be modified

    s.

url

=

"https://www.runoob.com"

    println

(

s.

url

)

}

Output result:



Runoob

www.runoob.com

https://www.runoob.com

Conversely, overriding a superclass var with a subclass val makes the compiler report "Var-property cannot be overridden by val-property".


super disambiguation

When a class implements multiple interfaces that provide default implementations of a same-named member, the subclass must override it explicitly and use super< to specify which one to call.

This form does not occur with single inheritance between classes; it only appears with multiple interfaces.

Example

// File path: Main.kt

interface

A

{

    fun foo

(

)

:

String

=

"A.foo"

}

interface

B

{

    fun foo

(

)

:

String

=

"B.foo"

}

class

C

:

A, B

{

   

// Both interfaces have default implementations; you must override and call each one

    override fun foo

(

)

:

String

=

super

<

A

.

foo

(

)

" | "

super

<

B

.

foo

(

)

}

fun main

(

)

{

    println

(

C

(

)

.

foo

(

)

)

}

Output result:



A.foo | B.foo

The same rule applies to properties in interfaces, e.g. super.label。


Override rules and final

Override-related rules are gathered here for reference while writing code.

Member state Can it be inherited Can it be overridden Description
Ordinary class (no modifier) No Not applicable Classes are final by default
open class Is Not applicable Must be explicitly opened
Ordinary method (no modifier) Is No Members are final by default
open method Is Is Subclasses can override
override method Is Is Still open by default after overriding
final override method Is No Ends the override chain
abstract method Is Must be overridden Abstract members are inherently open

When overriding, note that visibility cannot be tightened: if a superclass member is public, a subclass cannot override it as protected or private.


Common questions

The following are the most error-prone areas in inheritance.

Why can't my class be inherited

Kotlin classes are final by default; just add open before class, and the same goes for methods.

Must I write override when overriding

Yes. Kotlin uses override to express intent explicitly; omitting it produces errors like "hides member of supertype" or "needs override".

How to initialize the superclass when the subclass has no primary constructor

Use super(...) in every secondary constructor, or delegate to another secondary constructor that has already initialized the superclass.

Can a val property be overridden as var

Yes, but not the other way around. Because var has one more setter than val, adding capability is allowed but removing it is not.

super and super what is the difference

super is used with single inheritance and points to the sole superclass; super is used with multiple interfaces to explicitly specify a particular supertype's implementation.