问题描述
抱歉,我之前没有正确地提出问题.我试图冒犯工厂模式.一个更好的例子:它是一个抽象类Human,具有一个函数create.基于传递给创建者的参数,它决定是返回其子类Man的实例还是返回子类Woman的实例.因此,您可以通过以下方式调用create:Human john = Human.create("Man");
子类Man和Woman继承于抽象类Human,并且在与Human相同的文件中定义.我不希望通过以下方式扩展它:Human lisa = new Human("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!
感谢所有帮助!我最终使用的解决方案是让Human类成为公共类,并创建其功能. Human构造函数以及Man和Woman类被声明为受包装保护".
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".
推荐答案
不要在A的类声明中使用可见性说明符,它将是程序包访问类.
Don't use a visibility specifier in the class declaration for A and it will be a package access class.
编辑以反映有问题的更改:
选项1:将Human包的构造函数设为私有.这样,任何尝试将Human扩展到包之外的类都将失败,因为它无法调用超类的构造函数.
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.
选项2:坚持我对软件包私有类的最初建议,而改用公共访问工厂类.
Option 2:Stick with my original suggestion of a package private class and use instead a public access factory class.
这篇关于如何限制匿名子类(Java)的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!