我有以下类,但无法编译:
public class C {
public String toString() {
return "Test " + super;
}
}
它给出了编译错误 token “super”上的语法错误,无效的表达式
。
有谁知道为什么会出现这个编译器错误?预期的效果是 "Test "+ super.toString()
,编译正常,但是为什么上面的例子编译失败呢?字符串连接的普通 Java 规则不应该适用于此吗?
更令人惊讶的是,以下代码可以正常编译:
public String toString2() {
return "Test " + this;
}
那么为什么 this
在字符串连接中可以工作,而 super
却不能呢?
我正在使用openjdk 11.0.3 2019-04-16
,以防万一它很重要(我对此表示怀疑)。
最佳答案
Java 中的 super
关键字不是对象引用,因此您的代码中会出现一些错误!
这样做不是一个好的做法,因为 super
是发现父类的关键字。因此您无法使用该关键字进行打印!
根据 Java 规范:
The forms using the keyword super are valid only in an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If they appear anywhere else, a compile-time error occurs.
关于java - 在字符串连接中使用 super 时编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55940329/