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

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.

主站蜘蛛池模板: 井研县| 建始县| 鹤峰县| 天等县| 弋阳县| 云龙县| 平定县| 含山县| 郧西县| 西充县| 安远县| 天等县| 桑植县| 米脂县| 漾濞| 和林格尔县| 丹巴县| 特克斯县| 汾阳市| 绥芬河市| 武川县| 阿图什市| 石屏县| 鄯善县| 甘泉县| 临城县| 南川市| 满洲里市| 玛沁县| 福鼎市| 若尔盖县| 张家港市| 天水市| 凤台县| 聂荣县| 漠河县| 清新县| 酉阳| 渑池县| 陇西县| 阿鲁科尔沁旗|