What is a primary constructor in Kotlin?
What is a primary constructor in Kotlin?
A primary constructor in Kotlin is a concise way to initialize a class and its properties. It is part of the class header and goes after the class name, enclosed in parentheses. The primary constructor can have parameters that are used to initialize the class properties[1][2].
Here's an example of a class with a primary constructor:
class Person(val name: String, var age: Int) {
// class body
}
In this example, the primary constructor declares two properties: name
(read-only) and age
(read-write). When an object of the Person
class is created, the values passed to the constructor will initialize these properties[2].
The primary constructor can also be used with initializer blocks prefixed with the init
keyword. These blocks are executed when an instance of the class is created and can contain additional initialization logic[1][2].
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào