简体   繁体   中英

Overriding nested class member

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
   } 
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM