Sobes.tech
Middle

How to separate class and object methods and properties?

sobes.tech AI

Answer from AI

Methods and properties of a class belong to the class itself, not to a specific instance (object). They are defined using the static keyword. Methods and properties of an object (instance) belong to a specific object created based on the class.

Properties:

  • Class properties: Common to all objects of this class. Changing a class property in one place is visible in all other places that refer to this class.
  • Object properties: Unique to each instance of the class. Changing an object property does not affect other objects of the same class.

Methods:

  • Class methods: Called directly on the class, without creating an object. They are often used for factory methods or utility functions that do not depend on the state of a specific object. They do not have access to object properties.
  • Object methods: Called on a specific instance of the class. They have access to both the object's properties and the class properties.

Example in Kotlin:

class ExampleClass {
    // Class property (static): common to all instances
    companion object {
        const val CLASS_PROPERTY = "I am a class property"
    }

    // Object property: unique to each instance
    var objectProperty: String = "I am an object property"

    // Class method (static): called without creating an object
    companion object {
        fun classMethod() {
            println("I am a class method")
            // Cannot directly access objectProperty from here
        }
    }

    // Object method: called on a specific instance
    fun objectMethod() {
        println("I am an object method")
        println("Access to objectProperty: $objectProperty")
        println("Access to CLASS_PROPERTY: $CLASS_PROPERTY")
    }
}

fun main() {
    // Using class properties and methods
    println(ExampleClass.CLASS_PROPERTY)
    ExampleClass.classMethod()

    // Creating and using an object
    val obj1 = ExampleClass()
    obj1.objectProperty = "Value for obj1"
    println(obj1.objectProperty)
    obj1.objectMethod()

    val obj2 = ExampleClass()
    // objectProperty for obj2 has the default value
    println(obj2.objectProperty)
    obj2.objectMethod()
}
How to separate class and object methods and… - sobes.tech