Careeroza
Classes and Objects
What is a Class?
A class is a blueprint. An object is a real thing built from that blueprint. A Car class describes what every car has (brand, speed) and can do (drive). Each object made from it holds its own values.
- Declare a class with the
classkeyword. - Create an object by calling the class like a function:
Car(). Kotlin has nonewkeyword. - Variables inside a class are properties; functions inside a class are member functions (methods).
Create a Class and Objects
Example
Two objects from the same class keep separate values.
class Car {
var brand = ""
var speed = 0
fun drive() {
println("$brand is driving at $speed km/h")
}
}
fun main() {
val car1 = Car()
car1.brand = "Tata Nexon"
car1.speed = 80
val car2 = Car()
car2.brand = "Maruti Swift"
car2.speed = 60
car1.drive()
car2.drive()
}Output
Tata Nexon is driving at 80 km/h Maruti Swift is driving at 60 km/h
Properties in the Constructor
Setting every property after creating the object is long and error-prone. Usually you pass values in the class header. Writing val or var in front of a parameter turns it into a property.
Example
class Student(val name: String, var marks: Int)
fun main() {
val s = Student("Priya", 82)
println(s.name + " scored " + s.marks)
s.marks = 91 // var: can change
// s.name = "Riya" // val: compile error
println("Updated marks: " + s.marks)
}Output
Priya scored 82 Updated marks: 91
Exercise
Exercise: Create a class Book with title (val) and price (var). Create one book, raise its price by 50 and print both values.
Show answer
class Book(val title: String, var price: Int)
fun main() {
val b = Book("Kotlin in Action", 450)
b.price += 50
println("${b.title} costs ${b.price}")
}