Java:调用与接口字段冲突的抽象类的非静态字段

发布于 2025-01-15 04:35:28 字数 885 浏览 3 评论 0原文

如何显示抽象类 Confused("ConfusedValue") 中“name”非静态字段的值? 我尝试了3种方法,但都有错误。我只能显示 Confuslable 的名称值(“ConfusableValue”)

interface Confusable {
    String name = "ConfusableValue";

    String confuse();
}

abstract class Confused {
    String name = "ConfusedValue";

    abstract Object confuse();
}

public class Test extends Confused implements Confusable {
    public static void main(String[] args) {
        Test a = new Test();
        // --- OK
        System.out.println("Confusable.name: " + Confusable.name);
        // --- Errors
        System.out.println("name: " + name); // Error : The field name is ambiguous
        System.out.println("Confused.name: " + Confused.name); // Error : Cannot make a static reference to the non-static field Confused.name
        System.out.println("a.name: " + a.name); // Error : The field a.name is ambiguous
    }
}

How to display the value of the "name" non-static field from the abstract class Confused("ConfusedValue") ?
I tried 3 ways, but all have errors. I can display only the Confuslable's name value("ConfusableValue")

interface Confusable {
    String name = "ConfusableValue";

    String confuse();
}

abstract class Confused {
    String name = "ConfusedValue";

    abstract Object confuse();
}

public class Test extends Confused implements Confusable {
    public static void main(String[] args) {
        Test a = new Test();
        // --- OK
        System.out.println("Confusable.name: " + Confusable.name);
        // --- Errors
        System.out.println("name: " + name); // Error : The field name is ambiguous
        System.out.println("Confused.name: " + Confused.name); // Error : Cannot make a static reference to the non-static field Confused.name
        System.out.println("a.name: " + a.name); // Error : The field a.name is ambiguous
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韵柒 2025-01-22 04:35:29

字段名称不会被继承。他们只是互相影子。这是编译器关心的问题,但就运行时而言,它们都是独立存在的,只是碰巧共享一个名称。

因此,我们只需要使类型对于编译器来说看起来正确,并且我们可以通过显式向上转换来做到这一点。这些是向上转换(即扩大转换),因此它们是安全的并且保证会成功。

System.out.println("The method confuse returns: " + ((Confused)a).name);
System.out.println("The method confuse returns: " + ((Confusable)a).name);

Field names are not inherited. They merely shadow each other. That's a concern for the compiler, but as far as the runtime is concerned, they both exist independently and just so happen to share a name.

So we just need to make the types look right to the compiler, and we can do that with explicit upcasts. These are upcasts (i.e. widening conversions), so they're safe and guaranteed to succeed.

System.out.println("The method confuse returns: " + ((Confused)a).name);
System.out.println("The method confuse returns: " + ((Confusable)a).name);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文