简体   繁体   English

覆盖嵌套的类成员

[英]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.

相关问题 java嵌套类的数据成员 - java nested class data member 在春季重写父类受保护的成员变量注释 - Overriding parent class protected member variable annotations in spring 如何访问由外部类的成员隐藏的嵌套类的成员 - How to access a member of a nested class, that is hidden by a member of the outer class 确定成员类是嵌套还是内部? - Determine whether member class is nested or inner? 当嵌套类与封闭类的静态成员共享名称时,访问嵌套类的静态成员? - Access static member of nested class when nested class shares a name with a static member of the enclosing class? 覆盖嵌套在Java中参数化外部类中的非参数化类 - Overriding non-parameterized classes nested in a parameterized outer class in Java 如何从Java中的嵌套类访问父类成员? - How to access parent class member from nested class in Java? 用嵌套在另一个扩展Comparable的类中的类覆盖compareTo方法 - Overriding the compareTo method with a class that is nested inside another class which extends Comparable Drools规则表达式:访问嵌套类数据成员 - Drools Rule Expression : Access Nested class data member Java:获取class成员列表,用于多级嵌套列表中的列表 - Java: Obtain class member list, for a list within multilevel nested list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM