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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay