在 Java 中向上转换 "this" 引用是否有意义?

Is there a point in upcasting "this" reference in Java?

我遇到了一段奇怪的代码。想知道有没有什么用处

class C extends B {
    int xB = 4;

    C() {
        System.out.println(this.xB);
        System.out.println(super.xB);
        System.out.println(((B)this).xB); // This is the weird code.
    }
}

程序打印 4、10、10。public class B 的 xB 字段的值为 10。

在Java中,只能直接继承单个class。但是你可以有多个间接 superclasses。这可以用于将 "this" 引用向上转换到其中之一吗?或者这是糟糕的编程习惯,我应该忘掉它吗?

So "((B)this)" basically acts as if it is "super". We could just use super instead of it.

它通常不会做与 super 相同的事情。

在这种情况下是这样,因为字段没有动态调度。它们由它们的编译时类型解析。你用演员表改变了这一点。

但是super.method()((SuperClass)this).method()不一样。方法在运行时根据实例的实际类型进行分派。类型转换根本不会影响这一点。

I was wondering if people are using this structure to upcast "this" to indirect superclasses.

他们不必这样做,因为他们不会像那样重复字段名称。

隐藏子类中的继承(可见)字段是不好的做法(正是因为它会导致像这样的混淆)。所以不要那样做,你想要有这个演员表。

而且在方法方面你根本不能 "upcast to indirect superclasses":你可以直接调用 super.method()(如果你在子类中),但不能像 super.super.method().

thisC 的一个实例,它可以向上转型到它的直接(例如 B)或间接(例如 Object)父级。

C c = this;
B b = (B)c;
Object o = (Object)c;

Is this bad programming practice and I should forget about it?

这是一种解决方法,因为多态性不适用于字段。这是一个不好的做法。为什么 C 需要声明 xB 如果它已经在 B 中定义并且 B 可以授予对其子类的访问权限以访问和使用该字段?确实很奇怪。