How to restrict creation of anonymous subclass (Java)

Sorry, the question was not previously mentioned by me earlier. I am trying to implement a Factory pattern. Best example: it's an abstract Human class with a create function. Based on the arguments passed to create, it decides whether to return an instance of its Human subclass or an instance of its Female subclass. Therefore, you call create with: Human john = Human.create("Man");

Subclasses Man and Woman inherit from the abstract class Man and are defined in the same file as Man. I do not want it to be renewable: Human lisa = new Human("woman") {};

From the main program. Thanks!

EDIT:

Thanks for the help! The solution I finally used was to allow the public Human class as well as its functions to be created. The Human constructor and the Man and Woman classes are declared "protected packages".

+2


a source to share


2 answers


Don't use the visibility specifier in the class declaration for A, and it will be the package accessor class.

Edit to reflect the change in the question:



Option 1: Make the constructors for the Human package private. Thus, any class that tries to extend Human outside of the package will fail because it cannot call the superclass's constructor.

Option 2: Stick to my original package private class suggestion and use the public access factory class instead.

+1


a source


It depends on what you mean by impossibility. If you want it to be statically applied, the only way to do it is to access the package of the class, but that doesn't restrict anonymous classes - it also restricts named classes. If you want to apply it at runtime you can do it in the constructor of the abstract class



 if (this.getClass().isAnonymousClass() && !this.getClass().getName().startsWith(packageName)) {
     throw new IllegalStateException("This class cannot be used as an anonymous inner class");
  }

      

0


a source







All Articles