DEV Community

Cover image for Objects and Classes in Kotlin
Amandeep Singh
Amandeep Singh

Posted on

Objects and Classes in Kotlin

Classes and objects

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.
Classes are blueprints

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
}
}
Enter fullscreen mode Exit fullscreen mode

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()  

Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

Output:

Green
Enter fullscreen mode Exit fullscreen mode

Thank You

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)