Sobes.tech
Junior — Middle

Which inner classes are automatically declared inside another class if their creation is not explicitly defined?

sobes.tech AI

Answer from AI

In Java and Kotlin, no inner classes are automatically declared inside a class unless explicitly defined by the developer. However, in Kotlin, there is a feature: if an object is declared inside a class with the keyword companion object, it automatically becomes a singleton associated with that class and is accessible without creating an instance of the class.

That is, if inner classes are not explicitly created, then there will be no inner classes. In Kotlin, companion object is the only automatically created object inside a class if it is declared.

Example in Kotlin:

class MyClass {
    companion object {
        val CONSTANT = 42
        fun create() = MyClass()
    }
}

// Usage:
val instance = MyClass.create()
val value = MyClass.CONSTANT

In Java, there are no such automatically created inner classes.

Which inner classes are automatically declared inside… - sobes.tech