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

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.

主站蜘蛛池模板: 日土县| 平利县| 高台县| 阳东县| 平昌县| 孝感市| 洪湖市| 福州市| 鹤峰县| 瑞昌市| 光山县| 隆回县| 霸州市| 仁怀市| 福鼎市| 宜丰县| 琼结县| 涟水县| 澄城县| 宿迁市| 福鼎市| 壤塘县| 阜平县| 福州市| 南和县| 阿拉善右旗| 兴宁市| 武鸣县| 长宁县| 武清区| 龙川县| 延寿县| 巴塘县| 庐江县| 大同县| 永川市| 嘉黎县| 巨野县| 莱西市| 鹿泉市| 西乌珠穆沁旗|