我想通过我的构造函数添加方法并在之后使用它:
RegularAxis lon = new RegularAxis(){
public String returnHello(){
return "hello";
}
};
lon.returnHello();
Run Code Online (Sandbox Code Playgroud)
我无法访问我的新方法。还有其他方法吗?
您可以将其作为同一语句的一部分进行调用:
new RegularAxis(){
public String returnHello(){
return "hello";
}
}.returnHello();
Run Code Online (Sandbox Code Playgroud)
var或者您可以使用 Java 10+ 中的变量捕获匿名类型(感谢@Lesiak):
var lon = new RegularAxis(){
public String returnHello(){
return "hello";
}
};
lon.returnHello();
Run Code Online (Sandbox Code Playgroud)
否则,您必须将其声明为适当的类:
class IrregularAxis extends RegularAxis {
public String returnHello(){
return "hello";
}
}
IrregularAxis lon = new IrregularAxis();
lon.returnHello();
Run Code Online (Sandbox Code Playgroud)