Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I restrict inheritance to package without using 'default'?

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?

like image 470
Florian Avatar asked Aug 09 '11 14:08

Florian


People also ask

How do you restrict inheritance?

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.

Does default members get inherited across the package?

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.

How do you make a Java package private?

"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.


2 Answers

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.

like image 98
Peter Lawrey Avatar answered Nov 04 '22 18:11

Peter Lawrey


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() { ... }
}
like image 24
highlycaffeinated Avatar answered Nov 04 '22 17:11

highlycaffeinated