如何限制匿名子类的创建(Java)
抱歉,我之前没有正确表述这个问题。我尝试实现工厂模式。一个更好的例子:它是一个带有 create 函数的抽象类 Human。根据创建时传递的参数,它决定是返回其子类 Man 的实例还是返回 Woman 子类的实例。因此,您可以使用以下命令调用 create: Human john = Human.create("Man");
子类 Man 和 Woman 继承自抽象类 Human,并在与 Human 相同的文件中定义。我不希望可以通过以下方式扩展它: Human lisa = new Human("woman") {};
从主程序。谢谢!
编辑:
感谢您的所有帮助!我最终使用的解决方案是让类Human成为公共的,以及它的函数create。 Human 构造函数以及 Man 和 Woman 类被声明为“受包保护”。
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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要在 A 的类声明中使用可见性说明符,它将是一个包访问类。
进行编辑以反映相关更改:
选项 1:
将 Human 包的构造函数设为私有。通过这样做,任何尝试在包之外扩展 Human 的类都将失败,因为它无法调用超类的构造函数。
选项2:
坚持我最初的包私有类建议,并使用公共访问工厂类。
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.
这取决于你所说的不可能是什么意思。如果您希望它静态强制执行,唯一的方法是使类包访问,但这并没有具体限制匿名类 - 它也限制命名类。如果你想在运行时强制执行它,你可以在抽象类的构造函数中执行此操作
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