Kotlin Class Features: Constructors, Modifiers, and Special Classes
This article explains Kotlin class declarations, covering primary and secondary constructors, visibility modifiers, and special class types such as enums, sealed classes, and data classes, with code examples illustrating each concept.
Kotlin's class declaration uses the class keyword, with optional class header and body, and supports primary and secondary constructors, various visibility modifiers, and special class types such as enums, sealed classes, and data classes.
Primary constructors are defined in the class header and can include annotations and the constructor keyword; parameters become public properties unless marked private . Initialization code belongs in init blocks, and mutable parameters require var .
class Person(private val name: String) {
fun sayHello() {
println("hello $name")
}
}When a primary constructor needs additional logic, an init block is used, and the parameter can be declared as var to allow modification.
class Person(private var name: String) {
init {
name = "Zhang Tao"
}
internal fun sayHello() {
println("hello $name")
}
}Secondary constructors are defined inside the class body using the constructor keyword and must delegate to the primary constructor, allowing additional property initialization.
class Person(private var name: String) {
private var description: String? = null
init {
name = "Zhang Tao"
}
constructor(name: String, description: String) : this(name) {
this.description = description
}
internal fun sayHello() {
println("hello $name")
}
}Kotlin adds final to classes and members by default; to allow inheritance, the open modifier is required. The internal modifier provides module‑level visibility, while private restricts access to the class.
Special class types include:
Enums, where each constant is an object and the generated class extends kotlin.Enum and implements Comparable .
Sealed classes, which define a restricted hierarchy similar to enums but allow multiple instances per subclass.
Data classes, which automatically generate component functions, equals , hashCode , and toString methods.
The article concludes with a preview of upcoming topics on inheritance, composition, and interfaces.
Hujiang Technology
We focus on the real-world challenges developers face, delivering authentic, practical content and a direct platform for technical networking among developers.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.