Kotlin supports both object oriented programming (OOP) as well as functional programming. Object oriented programming is based on real time objects and classes.
We have seen classes before, for example our MainActicity()
class.
Class is a blueprints of an objects. Classes define methods that operate on their object instances.
Syntax to use classes:
Kotlin classes are declared using keyword class.
class House {
var color: String = "white"
var numberOfWindows: Int = 2
var isForSale: Boolean = false
fun updateColor(newColor: String){
newColor = Color
}
}
Objects in Kotlin:
Object is an instance of a class. Usually, you define a class and then create multiple instances of that class. Object is used to access the properties and member function of a class. Kotlin allows to create multiple object of a class.
Syntax of Using Object in Kotlin:
var obj = House()
Using a class:- We use a class by creating a new Object Instance
class House {
var color: String = "white"
fun updateColor(newColor: String){
color = newColor
}
}
fun main(){
var myHouse = House()
myHouse.updateColor("Green") //Updates the color of the House
println(myHouse.color) // Will Print the new color of the House
}
Output:
Green
If you have doubt in any part you can ask it in the discussion section.
Wanna connect? connect with me on LinkedIn
Top comments (0)