I have some classes that I need to be able to extend within the same package. But I don't want for anyone else outside of my package to extend my classes. Classes in other packages need to be able to call my classes so I cannot use 'default'.
Is there any way (maybe through an interface) that I can achieve this?
To prevent inheritance, use the keyword "final" when creating the class. The designers of the String class realized that it was not a candidate for inheritance and have prevented it from being extended.
In other words, a default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.
"Package private" or "default" visibility modifier in Java is achieved by leaving out the visibility modifier (not the type). i.e. An improvement in the answer: Therefore, you do not need to explicitly declare any variable as package-private, no exception.
If you make your constructors package local, it can only be extended in the same package however public members can be accessed in any class if it is a public class.
I'd do this by creating a base class with default
visibility, then extend it with a public final
class that external classes can call into but not extend. For example:
class MyBase {
public void doSomething() { ... }
}
public final class PublicBase extends MyBase { }
class ExtendedBase {
@Override
public void doSomething() { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With