Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class returning instances of a private nested class

Tags:

java

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 instances of B.

My attempt:

public abstract class A {

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

    private class B {

    }

}

Which of course doesn't work. How can I achieve this?

like image 416
Voldemort Avatar asked Dec 03 '25 22:12

Voldemort


1 Answers

You can do what you want by making class B as private static:

public abstract class A {
  ...

  private static class B {
    ...
  }

}

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

Perhaps there's reasons that you make A as abstract and B as private inner class. I think the intension is that you want to expose only interface and hide the concrete implementation type. Because abstract class is for subclassing, this can be achieved by making B as subtype of A and declare the common interface in A.

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

Now, you can create the instance of B outside the scope of A, as long as you specify the type of the object as A, like this:

A b = A.getInstanceOfB();

It would be better to remove the sign of specific type from the method name, and specify it by transferring argument.

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

You can create the object of type what you need within the getInstance() factory method as specified argument.

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

public interface IB {...}

and

public abstract class A {
  ...
  private static class B implements IB {
    ...
like image 87
ntalbs Avatar answered Dec 06 '25 13:12

ntalbs