为什么不允许System.out.println(super)? [英] Why is System.out.println(super) not permitted?
问题描述
为什么不允许 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()
fromDerived
: "Derived". - the implementation of
Description()
fromDerived
: "Derived description" - the implementation of
toString()
fromBase
: "Base". - the implementation of
Description()
fromBase
: 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屋!