-
Notifications
You must be signed in to change notification settings - Fork 22
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
fun primaryConstructorDemo() {
val science = Science()
val history = History()
// val maths = Maths() // Cannot access '<init>': it is private in 'Maths'
}
// Class with default constructor(way 1)
class Science()
// Class with default constructor(way 2)
class History constructor()
// Class with private constructor
class Maths private constructor()
// Class with protected constructor constructor
class Computers protected constructor()
When using a secondary
or ternary
constructor etc we should call the primary constructor if the primary constructor has variables.
fun secondaryConstructorDemo(){
val mechanical = Mechanical(name = "CustomName", noOfPages = 10)
}
class Mechanical(val name:String){
constructor(name: String, noOfPages:Int) : this(name)
}
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")
}
}