1

I have a Parent class written in Java file

public class ParentClass {

    public static int method1() {
        return 1;
    }
}

I have a Child class written in kotlin

class ChildClass: ParentClass() {

    companion object {
        @JvmStatic
        fun childMethod1(): Int {
            return 100
        }

    }
}

Similarly, I have a child class written in Java

class JavaChildClass extends ParentClass {

    public static int childMethod1() {
        return 200;
    }
}

Now, in my main kotlin class, I am trying to access the methods,

val result1 = JavaChildClass.childMethod1() //Method in the Java child class 
val result2 = JavaChildClass.method1() //Method in the parent class

val result3 = ChildClass.childMethod1() //Method in Kotlin Child class
val result4 = ChildClass.method1() //Error, cannot access this method
dcanh121
  • 4,665
  • 11
  • 37
  • 84
  • 3
    It's because Kotlin doesn't inherit static fields/methods. Also, companion object is a singleton of the enclosing class. https://kotlinlang.org/docs/java-interop.html#inheritance-from-java-classes https://blog.mindorks.com/companion-object-in-kotlin https://www.reddit.com/r/Kotlin/comments/3oj1xm/how_to_refer_to_super_static_fields_in_kotlin_code/cvxxtan/?st=isc2avuz&sh=0f63921a https://stackoverflow.com/questions/39171469/how-do-i-access-a-java-static-method-on-a-kotlin-subclass?rq=1. Use the Parent Java class directly to access that static method. – Laksitha Ranasingha Feb 16 '22 at 22:39

0 Answers0