为什么不允许System.out.println(super)? [英] Why is System.out.println(super) not permitted?

查看:244
本文介绍了为什么不允许System.out.println(super)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不允许 System.out.println(超级)

System.out.println(this);

这没关系, this.toString()自动调用和打印。
当然,实例变量是OK而不是这个

This is OK and this.toString() is called and printed automatically. Of course, instance variable is OK instead of this.

然而,这个 super 可以按我所知的方式使用。

However, this and super can be used in same way as I know.

System.out.println(super);

那为什么会失败呢?我认为它应该隐含地调用 super.toString()
我已阅读Java规范文档,但我没有找到原因。

So why does this fail? I think it's supposed to call super.toString() implicitly. I have read Java specification document, but I haven't found the reason.

推荐答案

实现独立的变体打破虚拟方法调度的 super 将是一个非常糟糕的主意。

Implementing a standalone variant of super that breaks virtual method dispatch would be an extremely bad idea.

让我们考虑一下。

abstract class Base {
    abstract String Description();
    String toString() { return "Base"; }
}
class Derived extends Base {
    String Description() { return "Derived description"; }
    String toString() { return "Derived"; }

    static void use(Base instance) {
        System.out.println(instance.toString());
        System.out.println(instance.Description());
    }
}

现在,让我们接受你的建议并假设 super 有效并按照您的建议行事;然后我们可以写派生

Now, let us take your suggestion and suppose that super is valid and does what you suggest; then we may write in Derived:

class Derived extends Base {
    // Previous declarations omitted.
    void useSuper() { Derived.use(super); }
    void useThis() { Derived.use(this); }

    static void main() {
        Derived instance = new Derived();
        instance.useThis();
        instance.useSuper();
    }
}

现在,如果我理解你,你建议你main函数应按顺序打印:

Now, if I understood you, you suggest that the main function should print in order:


  • toString()的实现来自派生:派生。

  • 执行 Description()来自派生:派生描述

  • toString()的实现来自 Base :Base。

  • Description()的实现来自基础它不存在。我能想到的两个解决方案会导致更大的问题:

    • 提出异常:恭喜,您现在可以破解任何依赖于实际实现的抽象方法的程序,甚至不用考虑它。 (你怎么知道函数会调用抽象方法?)

    • Derived 返回实现:打破一致性。

    • the implementation of toString() from Derived: "Derived".
    • the implementation of Description() from Derived: "Derived description"
    • the implementation of toString() from Base: "Base".
    • the implementation of Description() from Base: It does not exist. And the two solutions I can think of leads to bigger problems:
      • Raise an exception: congratulations, you can now break any program which relies on abstract methods actually being implemented without even thinking about it. (How would you know that a function will call the abstract method?)
      • Return the implementation from Derived: breaks consistency.

      简而言之,使用单词 super 从概念上打破了面向对象的编程。

      In short, such a use of the word super conceptually breaks object-oriented programming.

      这篇关于为什么不允许System.out.println(super)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆