我在Java中看到过几个类似的例子,我希望有人可以解释发生了什么.看起来像一个新类可以内联定义,这对我来说似乎很奇怪.第一个打印输出行是预期的,因为它只是toString.然而第二个看起来像函数可以重写内联.这有技术术语吗?或者任何更深入的文档?谢谢!
如果我有以下代码:
public class Apple {
public String toString() {
return "original apple";
}
}
public class Driver {
public static void main(String[] args) {
System.out.println("first: " + new Apple());
System.out.println("second: " +
new Apple() {
public String toString() {
return "modified apple";
}
}
);
}
}
Run Code Online (Sandbox Code Playgroud)
代码输出:
first: original apple
second: modified apple
Run Code Online (Sandbox Code Playgroud)