For the sake of unit tests,I would need to override the definition of deriveCalculatedData in the NESTED class below.
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
}
}
答案 0 :(得分:0)
Yes it's possible. You just have to create a new implementation or extension of that nested 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);