CodeBlanks Logo Icon CodeBlanks

object vs class

Learn the difference between object and class.

object vs class

object and class serve different needs. An object declares a singleton with a single instance; it cannot be instantiated and is used directly by name. A class is a template from which many instances can be created.

Example: object Config { val version = "1.0" } has a single Config for the whole app. A class User(val name: String) creates multiple instances like User("Alex"), User("Mia"). Use object when a singleton is needed, class when multiple instances are needed. A wrong choice leads to shared-state pollution.

Using them together

In an application object and class are usually used together. A class represents instances while an object holds shared helpers and configuration.

Example: object Config { val version = "1.0" }; class User(val name: String). User("Alex") creates a separate instance per user, while Config.version holds a single value for the whole app. This separation clarifies state management: instance data goes in a class, global data in an object.

Practice object Config and class User together

Define an object named Config with a val version = "1.0" property. Define a class User(val name: String). In main print User("Alex").name and Config.version on separate lines with println.

Starter code

Main.kt
// Define the Config object
// Define the User class
// print both in main

Sample solution

Main.kt
object Config {
    val version = "1.0"
}

class User(val name: String)

fun main() {
    println(User("Alex").name)
    println(Config.version)
}

Expected output

Alex
1.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the object and class difference

Term Meaning
object Config Single instance
class User Multiple instances
User("Alex") New instance
Config.version Access by name

2 Which is used for configuration that must keep a single instance throughout the app?

  • abstract class
  • class
  • object Correct answer
  • interface

Explanation: An object provides a single instance; it suits configuration.

3 Complete object and class together

Question
object Config {
    val version = "1.0"
}

class ____(val name: String)
Answer
object Config {
    val version = "1.0"
}

class User(val name: String)

Explanation: class User is multi-instance, object Config is single-instance.

All lessons in Intermediate