[英]Overriding nested class member
For the sake of unit tests,I would need to override the definition of deriveCalculatedData in the NESTED class below. 为了进行单元测试,我将需要覆盖下面的NESTED类中的generateCalculatedData的定义。
Is it possible to achieve it through an anonymous class override? 是否可以通过匿名类重写来实现?
How would I invoke the non-default constructor thereafter? 此后我将如何调用非默认构造函数?
Class A{
static class B{
B(String a,String b){ ... }
int deriveCalculatedData(){....}
}
main(){
int i = new A.B(x,y).deriveCalculatedData();//Override,and create instance
}
}
Yes it's possible. 是的,有可能。 You just have to create a new implementation or extension of that nested
class
. 您只需要为该嵌套
class
创建一个新的实现或扩展。
Either by an anonymous class: 通过匿名类:
// pass arguments to constructor like normal
B b = new A.B(str1, str2){
@Override
int deriveCalculatedData(){
// your stuff
return -1;
}
};
Or by a whole new class file, so you can reuse it: 或通过一个全新的类文件,因此您可以重用它:
public class C extends A.B {
public C(String str1, String str2){
// pass arguments to super constructor
super(str1, str2);
}
@Override
int deriveCalculatedData(){
// your stuff
return -1;
}
}
// call it from somewhere with arguments
C c = new C(str1, str2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.