How do I restrict the creation of an anonymous subclass (Java)

孤人 提交于 2019-12-24 00:58:29

问题


Sorry the question wasn't properly stated by me earlier. I try to implent the Factory Pattern. A better example: It is an abstract class Human with a function create. Based on the arguments that is passed to create it decides whether to return an instance of its subclass Man or an instance of subclass Woman. So you call create with: Human john = Human.create("Man"); The subclasses Man and Woman are inherited from the abstract class Human and are defined in the same file as Human. I don't want it to be possible to extend it by: Human lisa = new Human("woman") {}; From the main program. Thanks!

EDIT:

Thanks for all the help! The solution I finally used was to let the class Human be public, as well as its function create. The Human constructor and the Man and Woman classes are declared "package-protected".


回答1:


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

Edit to reflect change in question:

Option 1: Make the constructors for Human package private. By doing this, any class which attempts to extend Human outside of the package will fail because it can not call a constructor of the super class.

Option 2: Stick with my original suggestion of a package private class and use instead a public access factory class.




回答2:


It depends what you mean by not possible. If you want it statically enforced, the only way to do that is to make the class package access, but that doesn't specifically limit anonymous classes - it limits named classes as well. If you want to enforce it at runtime, you can do this 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");
  }


来源:https://stackoverflow.com/questions/2692343/how-do-i-restrict-the-creation-of-an-anonymous-subclass-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!