DEV Community

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

Posted on

1

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

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay