简体   繁体   English

kotlin 中的静态最终字段继承

[英]Static final field inheritance in kotlin

I have a really simple question here, but can't figure it out.我在这里有一个非常简单的问题,但无法弄清楚。 Consider a java class:考虑一个java类:

class A {
    public static final int AA=5;
}

which translates (internally) into kotlin as this:将(内部)转换为 kotlin 如下:

open class A {
    companion object {
        val AA:Int=5
    }
}

At least that's what I assume.至少我是这么认为的。 Now if you inherit in java:现在,如果您在 Java 中继承:

class B extends A {
    int AAA;
}

you can access field AA (from A) through B like this: B.AA .您可以像这样通过 B 访问字段 AA(从 A): B.AA 。 However, in Kotlin it's impossible.但是,在 Kotlin 中这是不可能的。 The only way to access it is through A.AA.访问它的唯一方法是通过 A.AA。 Is this a built-in feature or I am doing something wrong?这是内置功能还是我做错了什么?

In Java, when the compiler sees B.AA , it automatically transforms it into A.AA .在 Java 中,当编译器看到B.AA ,它会自动将其转换为A.AA There's no real inheritance or overriding there.那里没有真正的继承或覆盖。

Kotlin's developers decided not to emulate this feature, because it doesn't fit with thinking of static methods as belonging to an object : the companion object of B doesn't extend the companion object of A , and can't because you can't extend an object . Kotlin 的开发人员决定不模拟此功能,因为它不符合将静态方法视为属于object想法: B的伴生对象不扩展A的伴生对象,并且不能,因为您不能扩展一个object

Note that similarly, in Java you can access the field via a.AA where a is an instance of A ;请注意,类似地,在 Java 中,您可以通过a.AA访问该字段,其中aA的实例; you can't do that in Kotlin either.你也不能在 Kotlin 中做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM