-
Notifications
You must be signed in to change notification settings - Fork 23
Kotlin Fundamentals: Classes
Devrath edited this page Jan 26, 2024
·
8 revisions
If you want to Inherit a class, You need to mark it as open
indicating that it can be inherited explicitly
This primary constructor is used to create an instance
We can mark it as val
or var
thus it becomes public
class Person(name: String)
class Student(val name: String)
fun test() {
val person = Person("Donald")
person.name // Unresolved reference: name
val student = Student("Einstein")
student.name // We can access the name variable
}
- We cannot execute the code in the constructor like how we did in Java
- If we want some code to be executed when the object is created we can use
init
block. - In the init block, We have access to the values passed to the constructor variables output
Before City Class construction
City is created with Name:-> New York
After City Class construction
City construction is in progress
code
fun initBlockSignificanceDemo() {
println("Before City Class construction")
val demo = City("New York")
println("After City Class construction")
demo.demo()
}
class City(val name: String){
init {
println("City is created with Name:-> $name")
}
fun demo(){
println("City construction is in progress")
}
}