简体   繁体   中英

How do I instantiate a nested private static class java

Lets say I have some nested classes

class A{
  private static class B{}
  static class C{ 
    B b;
    C(B b){
        this.b=b;
    }
    int foo(){
        return 42;
    }
  }
} 

I am trying to instantiate the private static class B by doing the following

new A.C(new A.B())

but because B is private I'm unable to do this. What is a way of constructing class C with a class B?

You can either make B non private, or provide a helper method in A to create C :

class A{
  private static class B{}
  static class C{ 
    B b;
    C(B b){
        this.b=b;
    }
    int foo(){
        return 42;
    }
  }
  static createC() {
    return new C(new B());
  }
} 

So that outside of A , you can create an instance of C like this:

A.C myc = A.create();

Note that since B is not visible outside, the constructor of C is useless, so you can make that private.

如果您只是想进行测试并绕过断言错误,那么您可以使用 b 的空值实例化 c,然后创建一个匿名类并覆盖 foo。

new AC(null){int foo(){return 42;}}

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