java - 在字符串连接中使用 super 时编译失败

标签 java inheritance tostring

我有以下类,但无法编译:

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/

相关文章:

c++ - 是否可以将派生类对象视为同类型的基类? <noobieQ/>

groovy - 在 Groovy 中将整数转换为十六进制字符串

java - Qt中Java窗体布局的模拟

java - CXF wsdl2java 导致 BINDING_MISSING_TYPE

java - 找出假数字的所有因素

c# - 从 System.Web.UI.Page 继承时 Session 为空

python - Django - 如何序列化继承

javascript - 什么时候使用 .toString() 是安全的?

c# - 通用类型 nullable 和 ToString

java - J2EE Struts、Spring 和 Hibernate 框架问题