我有以下两个课程,如下所示。为了简单起见,仅显示了 toString 重写方法。
public class Circle {
@Override
public String toString() {
return "Circle";
}
}
public class Cylinder extends Circle {
@Override
public String toString() {
// return "Cylinder"+this; // runs without explicitly calling toString() on this keyword
// return "Cylinder"+super; // throws error, asks to delete super token
return "Cylinder["+super.toString(); // runs without error after adding .toString() with super keyword
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我对 super 关键字的理解。super 关键字的 toString() 应该像 this 关键字一样隐式调用。事实上,大多数教程和书籍都将 super 关键字称为对超类的一种对象引用,因此它的行为必须与this 关键字与 toString() 内的“+”连接运算符一起使用。请帮助我理解这一点。