官术网_书友最值得收藏!

Classes in Kotlin

Classes in Kotlin are created using the class keyword, which is depicted as follows:

class User {

}

The structure of the class is as follows:

Class className {
//properties and constructor
//member functions
}

Let's write a class for User.

Consider the following code for 14_Class.kts:

class User {
var name = "George"
}

val user = User()
println(user.name)

The output is as follows:

This class has a property called name. Classes are instantiated with just the class name, followed by parentheses. Note that there is no new keyword in Kotlin to create an object, unlike in Java.

Classes in Kotlin are final by default. We cannot extend from a class directly. To inherit from the classes, we have to open the classes explicitly. Classes need to have an open keyword in their declaration, as shown in the following code:

open class Person {

}

Alternatively, we can use all-open compiler plugins to make all the classes extendable or accessible to frameworks such as JPA and Spring. We will discuss compiler plugins further in the next chapter.

主站蜘蛛池模板: 隆尧县| 扎囊县| 盐亭县| 桐城市| 顺义区| 双柏县| 措勤县| 丰城市| 微博| 遵义市| 双城市| 米脂县| 小金县| 钟祥市| 阿克陶县| 保亭| 永川市| 甘洛县| 葫芦岛市| 凤翔县| 瑞金市| 北川| 苏尼特右旗| 探索| 芜湖县| 申扎县| 绥滨县| 罗源县| 郧西县| 清水县| 庄河市| 汝州市| 如东县| 利津县| 开封市| 闽清县| 阿拉善左旗| 靖宇县| 扎鲁特旗| 鲁山县| 虞城县|