[英]Java: How to create a public class that can be subclassed within package, while preventing outsiders from inheriting?
Suppose I am writing a package. 假设我正在写一个包。 I have the following inheritance hierarchy, all within my package: 我的包中包含以下继承层次结构:
public class Container {
public void size() {
System.out.println(10);
}
}
public final class Bucket extends Container {}
public final class Bag extends Container {}
public class Item {
Container container; // is aware of what container it's in. Will be initialized on construction.
public Container getContainer() {
return container;
}
}
I want to prevent others from subclassing Container
. 我想防止其他人将Container
子类化。 But I can't make it final
because Bucket
and Bag
are subclasses. 但我不能让它final
因为Bucket
和Bag
是子类。 And I have to make it public
or else outsiders cannot call getContainer()
. 而且我必须将其public
,否则外界无法调用getContainer()
。 Is there a way to do this in Java? 有没有办法用Java做到这一点? Otherwise, what do people do in this type of situation? 否则,人们在这种情况下会做什么?
To prevent a class from being subclassed by classes in other packages, make all the constructors package-private . 为了防止某个类被其他包中的类子类化,请使所有构造函数使用package-private 。
If the class doesn't have any constructors, it has the implicit default constructor , which is public, so you need to explicitly create a package-private no-arg constructor. 如果该类没有任何构造函数,则它具有隐式默认构造函数 ,它是public,因此您需要显式创建一个包私有的无参数构造函数。
package foo;
public class Container {
Container () {/*package-private*/}
public void size() { System.out.println(10); }
}
package foo;
public final class Bucket extends Container {}
package bar;
public final class Oops extends Container {}
Compile Error: Implicit super constructor Container() is not visible for default constructor. 编译错误:对于默认构造函数,隐式超级构造函数Container()不可见。 Must define an explicit constructor 必须定义一个显式构造函数
public final class Oops extends Container {
public Oops() {}
}
Compile Error: Implicit super constructor Container() is not visible. 编译错误:隐式超级构造函数Container()不可见。 Must explicitly invoke another constructor 必须显式调用另一个构造函数
Of course, there are no other constructors, so it cannot be done. 当然,没有其他构造函数,因此无法完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.