Java – abstract classes return instances of private nested classes

I want an abstract class A

Then I want a class B that can only be instantiated by A No one else can access B – only a

Then I want a to have a method that returns an instance of B

My attempt:

public abstract class A {

    public static B getInstanceOfB() {
        return new B();
    }

    private class B {

    }

}

Of course it doesn't work How can I do this?

Solution

You can use class B as a private static to do what you want to do:

public abstract class A {
  ...

  private static class B {
    ...
  }

}

If class B is not static, there should be an instance of a to access B. If you want to instantiate B without instantiating a, you should make the inner class static

There may be reason to treat a as an abstract and B as a private inner class I think the content is that you just want to expose the interface and hide the specific implementation type Because abstract classes are used for subclassing, this can be achieved by taking B as a subtype of a and declaring a public interface in a

public abstract class A {
  ...
  private static class B extends A {
    ...

Now, you can create an instance of B outside the scope of a, as long as you specify the object type as a, as follows:

A b = A.getInstanceOfB();

It is best to remove a specific type of symbol from the method name and specify it by passing parameters

A b = A.getInstance(...);

You can create an object of the required type as a specified parameter in the getInstance () factory method

Well, if you shouldn't use a like this, you can declare a public interface for class B and use it as a type B outside the scope of A

public interface IB {...}

and

public abstract class A {
  ...
  private static class B implements IB {
    ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>