-
Notifications
You must be signed in to change notification settings - Fork 1
5. Classes and Objects
Ashwin Ramakrishnan edited this page Dec 15, 2021
·
3 revisions
Defined with the keyword class
.
class Car {
var speed: Int = 300
var mileage: Int = 50
var isHatchback: Boolean = false
fun printDetails(){
println("Your car has a max speed of $speed and mileage of $mileage. It is a ${if (isHatchback) "hatchback" else "sedan"}")
}
}
fun main() {
val jetta: Car = Car()
jetta.printDetails()
// OUTPUT: Your car has a max speed of 300 and mileage of 50. It is a sedan
println(jetta.speed) // Prints 300 as getter function is created for the class under the hood by Kotlin.
jetta.speed = 250 // Modifies speed as setter function is also created under the hood.
println(jetta.speed) // Prints 250
}
class Car(speed: Int = 300, mileage: Int = 50, isHatchBack: Boolean = false) {
var speed: Int = speed
var mileage: Int = mileage
var isHatchback: Boolean = isHatchBack
// ...
// Init blocks can be used when more code needs to be executed
// with the constructor.
init{
println("Obj initialized with values $speed $mileage $isHatchback ")
// Prints: "Obj initialized with values 300 60 true" for Car(mileage = 60, isHatchBack = true)
}
}
fun main() {
val polo: Car = Car(mileage = 60, isHatchBack = true) // Uses the default value 300 for speed
polo.printDetails()
}
Used to perform constructor overloading.
class Car(speed: Int = 300, mileage: Int = 50, isHatchBack: Boolean = false) {
// ...
constructor(isRollsRoyce: Boolean) : this() {
if(isRollsRoyce){
// Assigning special values for Rolls Royce
speed = 500
mileage = 50
isHatchback = false
}
}
// ...
}
fun main() {
// Uses the secondary constructor to define its values
val royce: Car = Car(isRollsRoyce = true)
}
Can be used to execute code while getting/setting individual values.
class Car(speed: Int = 300, mileage: Int = 50, isHatchBack: Boolean = false) {
var mileage: Int = mileage
var speed: Int = speed
get() = field //field is a keyword that references to speed in this case
set(value){
if(value >= 500){
mileage = 5
}
field = value
}
var isHatchback: Boolean = isHatchBack
// ...
}
fun main() {
val royce: Car = Car(isRollsRoyce = true)
royce.speed = 500 // Calls the explicitly defined setter and sets speed to 500 as well as mileage to 5
println(royce.mileage) // Prints 5
}
-
public
= visible outside the class. Everything is public by default. -
internal
means it will only be visible within the module. A module is a set of Kotlin files compiled together, for example, a library or application. -
private
means it will only be visible in that class (or source file if you are working with functions). -
protected
is the same as private, but it will also be visible to any subclasses.