0

I tried to access variable STR_PARENT from ParentClass.kt in Activity function like ChildClass.STR_PARENT, but it doesn't allow. How to achieve it.

open class ParentClass {

    companion object {

        const val STR_PARENT = "str_parent"
    }
}

class ChildClass : ParentClass() {

    companion object {

        const val STR_CHILD = "str_child"
    }
}

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ChildClass.STR_CHILD // works
        ParentClass.STR_PARENT // works
        ChildClass.STR_PARENT // doesn't work
    }
}

As you can see, in onCreate function I can access variable like : ParentClass.STR_PARENT, but I can't access same variable like : ChildClass.STR_PARENT in Kotlin. Same thing is possible in Java but in Kotlin it is not working.

I didn't find anything regarding this in Kotlin inheritance doc too.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
Krunal Panchal
  • 384
  • 2
  • 3
  • 12
  • Have you try: ChildClass.super.STR_PARENT – Twistleton Mar 03 '21 at 12:48
  • Yes tried, it didn't work too. We can't event use like : ChildClass.super @Twistleton – Krunal Panchal Mar 03 '21 at 12:50
  • It is not possible to access the static variable from Parent class except reflection – guest Mar 03 '21 at 13:15
  • 2
    Does this answer your question? [Kotlin: How can I create a "static" inheritable function?](https://stackoverflow.com/questions/39303180/kotlin-how-can-i-create-a-static-inheritable-function) – Sharp Mar 03 '21 at 13:18
  • You already answered your question in your example: `ParentClass.STR_PARENT // works` You have to use the proper class name. Companion objects are not inherited by subtypes. – Tenfour04 Mar 03 '21 at 13:52

0 Answers0