Posts

Showing posts with the label access-modifiers

Java: How to create a public class that can be subclassed within package, while preventing outsiders from inheriting?

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 . But I can't make it final because Bucket and Bag are subclasses. And I have to make it public or else outsiders cannot call getContainer() . Is there a way to do this in Java? Otherwise, what do people do in this type of situation? Container final Bucket Bag public getContainer() So to clarify what you may be aski...