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

Kotlin Classes and Objects

Kotlin Classes and Objects

A class encapsulates data and behavior, and an object is a concrete instance of a class.

This chapter starts with the simplest empty class and gradually covers properties, constructors, initializer blocks, nested classes, and access modifiers, which lay the groundwork for learning inheritance and interfaces later.


Definition of the class

Kotlin defines a class with the class keyword; the class name can be followed by a primary constructor, and the class body is written in braces.

Creating an object does not require the new keyword; just write the class name followed by parentheses, which differs from Java.

Example

// File path: Main.kt

// Empty class: with no class body, the braces can be omitted

class

Runoob

// A class with an empty primary constructor, equivalent to the above

class

RunoobSite

(

)

fun main

(

)

{

   

// No new needed; call the class name directly to create an object

    val a

=

Runoob

(

)

    val b

=

RunoobSite

(

)

    println

(

"Type of a: ${a::class.simpleName}"

)

    println

(

"Type of b: ${b::class.simpleName}"

)

}

Output result:



a 的类型:Runoob

b 的类型:RunoobSite

class Runoob and class Runoob() behave identically when creating objects; the only difference is whether the primary constructor is written explicitly.


Properties and getter/setter

Inside the class body, use val to declare a read-only property and var to declare a mutable property.

Every property comes with a getter, and var properties also come with a setter; you can write your own when you need custom behavior.

Example

// File path: Main.kt

class

Site

{

    var name

:

String

=

"RUNOOB"

         

// var property: has a getter and a setter

    val url

:

String

=

"www.runoob.com"

   

// val property: has only a getter

   

// Custom getter: recomputes on every access, with no backing field

    val info

:

String

        get

(

)

=

"$name - $url"

   

// Custom setter: value is the conventional parameter name

    var visits

:

Int

=

0

        set

(

value

)

{

           

if

(

value

<

0

)

{

println

(

"Visits cannot be negative; ignored"

)

           

}

else

{

                field

=

value

           

}

       

}

}

fun main

(

)

{

    val site

=

Site

(

)

    println

(

site.

info

)

    site.

visits

=

100

    println

(

"Visits: ${site.visits}"

)

    site.

visits

=

1

    println

(

"Visits: ${site.visits}"

)

}

Output result:



RUNOOB - www.runoob.com

访问量:100

访问量不能为负,已忽略

访问量:100

Inside a setter, value is the new value and field is the property's actual storage location; field can only be written inside a getter or setter.


The backing field

Kotlin does not expose member variables directly but accesses them through getters and setters; the field that actually stores the value is called the backing field.

Only properties that truly need to store a value get a backing field; read-only computed properties do not.

Example

// File path: Main.kt

class

Counter

{

    var count

:

Int

=

0

        get

(

)

=

field        

// field is the backing field

        set

(

value

)

{

            field

=

value

       

}

   

// Read-only computed property: no backing field, recomputed on every access

    val doubleCount

:

Int

        get

(

)

=

count

2

}

fun main

(

)

{

    val c

=

Counter

(

)

    c.

count

=

21

    println

(

"count:${c.count}"

)

    println

(

"doubleCount:${c.doubleCount}"

)

}

Output result:



count:21

doubleCount:42

Note:If neither the custom getter nor the setter uses field, no backing field is generated for the property, making it essentially an entry point that only computes or forwards.


Primary Constructors and the Rules for Omitting constructor

The primary constructor is written after the class name; adding val or var before a parameter also declares a property.

When there are no annotations and no visibility modifiers, the constructor keyword can be omitted.

Example

// File path: Main.kt

// The primary constructor declares properties directly: val read-only, var mutable

class

Site

(

val name

:

String

, var visits

:

Int

)

{

   

// constructor is omitted because there are neither annotations nor visibility modifiers

    init

{

        println

(

"Creating site: $name, initial visits: $visits"

)

   

}

}

fun main

(

)

{

    val site

=

Site

(

"RUNOOB"

,

0

)

    site.

visits

=

10

    println

(

"${site.name} visits: ${site.visits}"

)

}

Output result:



创建站点:RUNOOB,初始访问量:0

RUNOOB 访问量:10

If a parameter is not preceded by val or var, it is just a constructor parameter, not a property, and can only be used in initializer blocks and property initializers.

When the primary constructor has a visibility modifier or annotations, the constructor keyword cannot be omitted, for example, private constructor. You'll see the exact syntax in the "Private Constructors" section later.


The init Initializer Block

The init block holds code that must run when an object is created, and you can write multiple ones.

Flowchart of Kotlin class initialization order: primary constructor parameters are evaluated, then property initializers and init blocks run interleaved in source order, then the secondary constructor body runs, and finally the object is ready to use

Property initializers and init blocks execute in the order they are written; understanding this order is important for troubleshooting initialization issues.

Example

// File path: Main.kt

class

Demo

(

val name

:

String

)

{

   

// Property initializers and init blocks execute in writing order

   

private

val first

=

"First property: $name"

.

also

{

println

(

it

)

}

    init

{

        println

(

"init block: $name"

)

   

}

   

private

val second

=

"Second property: $name"

.

also

{

println

(

it

)

}

}

fun main

(

)

{

    Demo

(

"RUNOOB"

)

}

Output result:



第一个属性:RUNOOB

init 块:RUNOOB

第二个属性:RUNOOB

So don't read, in later initialization code, a nullable property that was written earlier but hasn't finished being assigned, or you'll likely get null.


Secondary Constructors and this Delegation

A secondary constructor is declared with the constructor keyword and written inside the class body.

If a class has a primary constructor, every secondary constructor must delegate to it directly or indirectly, using this(...).

Example

// File path: Main.kt

class

Site

(

val name

:

String

, val url

:

String

)

{

    var visits

:

Int

=

0

   

// The secondary constructor must delegate to the primary constructor; here we supply a default address

    constructor

(

name

:

String

)

:

this

(

name,

"www.runoob.com"

)

{

        println

(

"Created with secondary constructor: $name"

)

   

}

}

fun main

(

)

{

    val a

=

Site

(

"RUNOOB"

,

"www.runoob.com"

)

    println

(

"${a.name} -> ${a.url}"

)

    val b

=

Site

(

"Runoob"

)

    println

(

"${b.name} -> ${b.url}"

)

}

Output result:



RUNOOB -> www.runoob.com

使用次构造器创建:Runoob

Runoob -> www.runoob.com

Along the delegation chain, the primary constructor's parameters are ready first, followed by the secondary constructor's body, hence the print order above.


Private Constructors

Marking the primary constructor as private prevents outside code from creating objects directly; instances can only be obtained through a factory method provided inside the class.

This pattern is commonly used for singletons, utility classes, and scenarios where you want to control the instance creation process.

Example

// File path: Main.kt

class

Token

private

constructor

(

val value

:

String

)

{

   

// Outside code cannot call Token("..."); it can only use this factory method

    companion object

{

        fun create

(

)

:

Token

=

Token

(

"runoob-token"

)

   

}

    fun describe

(

)

:

String

=

"Token($value)"

}

fun main

(

)

{

   

// val t = Token("abc") // Compile error: the constructor is private

    val token

=

Token.

create

(

)

    println

(

token.

describe

(

)

)

}

Output result:



Token(runoob-token)


abstract classes

A class marked with abstract is an abstract class; it cannot be instantiated, only inherited.

An abstract class can contain both abstract and ordinary members; abstract members must be implemented by subclasses.

Example

// File path: Main.kt

abstract

class

Shape

{

   

// Abstract members have no implementation and must be overridden by subclasses

   

abstract

fun area

(

)

:

Double

   

// Ordinary members are final by default; add open to allow overriding

    open fun describe

(

)

:

String

=

"The area is ${area()}"

}

class

Circle

(

val radius

:

Double

)

:

Shape

(

)

{

    override fun area

(

)

:

Double

=

3.14

radius

radius

}

class

Square

(

val side

:

Double

)

:

Shape

(

)

{

    override fun area

(

)

:

Double

=

side

side

    override fun describe

(

)

:

String

=

"Square"

super

.

describe

(

)

}

fun main

(

)

{

   

// val s = Shape() // Compile error: an abstract class cannot be instantiated

    val shapes

:

List

<

Shape

=

listOf

(

Circle

(

2.0

)

, Square

(

3.0

)

)

   

for

(

shape in shapes

)

{

        println

(

shape.

describe

(

)

)

   

}

}

Output result:



面积是 12.56

正方形面积是 9.0

Note that abstract fun area() is inherently open, but for describe() to be overridden by subclasses, you must add open explicitly.


Nested Classes and Inner Classes

A class written inside another class body is a nested class and by default holds no reference to the outer class.

If you want to access the outer class's members, add the inner keyword; it then becomes an inner class, and you can use this@Outer to refer explicitly to the outer class instance.

Example

// File path: Main.kt

class

Outer

(

val name

:

String

=

"OUTER"

)

{

   

private

val secret

=

"runoob"

   

// Nested class: holds no reference to the outer class instance and cannot access name or secret

   

class

Nested

{

        fun hello

(

)

:

String

=

"I am a nested class and cannot access the outer class's members"

   

}

   

// Inner class: holds a reference to the outer class instance and can access its members

    inner

class

Inner

{

        fun hello

(

)

:

String

=

"I am an inner class, name=$name, secret=$secret"

       

// this@Outer explicitly refers to the outer class instance

        fun outerName

(

)

:

String

=

this

@Outer.

name

   

}

}

fun main

(

)

{

   

// A nested class is accessed directly by the outer class name, with no outer class object needed

    val nested

=

Outer.

Nested

(

)

    println

(

nested.

hello

(

)

)

   

// An inner class must depend on an outer class instance

    val outer

=

Outer

(

)

    val inner

=

outer.

Inner

(

)

    println

(

inner.

hello

(

)

)

    println

(

"this@Outer gets: ${inner.outerName()}"

)

}

Output result:



我是嵌套类,拿不到外部类的成员

我是内部类,name=OUTER,secret=runoob

this@Outer 拿到:OUTER

A nested class has no extra outer reference and is more lightweight; an inner class implicitly holds an outer class object, so be mindful of memory.


Anonymous Inner Classes

An object expression can create a class without a name, usually to implement an interface or abstract class temporarily.

An object expression creates an instance the moment it is written, with no separate class declaration needed.

Example

// File path: Main.kt

interface

ClickListener

{

    fun onClick

(

name

:

String

)

}

fun main

(

)

{

   

// Object expression: temporarily implementing the ClickListener interface

    val listener

=

object

:

ClickListener

{

        override fun onClick

(

name

:

String

)

{

            println

(

"Clicked: $name"

)

       

}

   

}

    listener.

onClick

(

"RUNOOB"

)

   

// When not implementing any interface, you can also write an anonymous object directly

    val config

=

object

{

        val url

=

"www.runoob.com"

        val timeout

=

3000

   

}

    println

(

"${config.url} -> ${config.timeout}ms"

)

}

Output result:



点击了:RUNOOB

www.runoob.com -> 3000ms

Note:If an anonymous object is used as the return type of a public function, outside code can only see its declared supertype (such as an interface type) and cannot access members added by the anonymous object itself; this detail is covered in Chapter 21, "Kotlin Object Expressions and Object Declarations" will be expanded.


Class Modifiers and Access Modifiers

A class itself can carry various modifiers to control inheritance, instantiation, and generated special behavior.

Modifiers Meaning
final By default, a class cannot be inherited
open Can be inherited
abstract Abstract class; cannot be instantiated, members can be abstract
sealed Sealed class; subclass scope is restricted, see Chapter 19, "Kotlin Sealed Classes and Sealed Interfaces》
data Data class; automatically generates equals, hashCode, toString, and copy, see Chapter 18, "Kotlin Data Classes and Destructuring》
enum Enum class; see Chapter 20, "Kotlin Enum Classes》
inner Inner class; holds a reference to the outer class instance
value Value class; used with @JvmInline, see Chapter 25, "Kotlin Value Classes》

Access modifiers control who can see a member; there are four in total.

Modifiers Visibility scope of class members Top-level declarations
public (default) Anywhere Anywhere
internal Within the same module Within the same module
protected Only inside this class and its subclasses Not allowed for top-level declarations
private Only inside this class Only inside this file

Example

// File path: Main.kt

open

class

Base

{

   

private

val a

=

"private: visible only inside this class"

   

protected

val b

=

"protected: visible only inside this class and its subclasses"

    internal val c

=

"internal: visible within the same module"

    val d

=

"public: default, visible anywhere"

    fun showBase

(

)

{

        println

(

a

)

        println

(

b

)

   

}

}

class

Derived

:

Base

(

)

{

    fun showDerived

(

)

{

       

// println(a) // Compile error: even subclasses cannot see a private member

        println

(

b

)

     

// Allowed: protected is visible inside subclasses

        println

(

c

)

        println

(

d

)

   

}

}

fun main

(

)

{

    val base

=

Base

(

)

    base.

showBase

(

)

   

// println(base.b) // Compile error: outside code cannot access a protected member

    val derived

=

Derived

(

)

    derived.

showDerived

(

)

}

Output result:



private:仅本类内部可见

protected:仅本类及其子类内部可见

protected:仅本类及其子类内部可见

internal:同一模块内可见

public:默认,任何位置可见

Important correction:Kotlin's protected is visible only "inside this class and its subclasses" and has nothing to do with files or packages; outside code cannot access it even in the same file. Being visible within the same file is the semantics of top-level private, don't confuse the two.

Once more: protected is tied to inheritance, internal is tied to modules; the former requires being a subclass, the latter only requires being in the same module.


Common questions

Below are the points that most often trip up beginners learning classes and objects.

What happens if a primary constructor parameter has no val or var

It is just a constructor parameter, not a property. It can be used by property initializers and init blocks but cannot be accessed through the object.

Which runs first, the init block or property initializers

They execute in writing order, whichever is written first runs first, regardless of whether it is an init block.

Why must a secondary constructor call this(...)

When a class has a primary constructor, it is responsible for initializing properties; a secondary constructor must delegate to it directly or indirectly, otherwise the properties cannot be fully initialized.

How to choose between nested and inner classes

Use a nested class when you don't need outer class members, it's more lightweight; use inner only when you need to access outer class members.

Can an abstract class have ordinary members

Yes. An abstract class can have both abstract members and ordinary members with implementations; these ordinary members are final by default, so add open to allow overriding.