简体   繁体   中英

A Java method that can only be called by its own class or by other subclasses

I'd like my class to have a method that can only be called by itself or by its subclasses.

The closest thing is protected access, but it also allows other classes in the same package to call the method, which I don't want.

Is there a way to achieve this, or should I consider some sort of package refactoring instead?

It seems to me like private won't let subclasses use the method.

See In Java, difference between default, public, protected, and private

There is no such thing. But you can move the class in an empty package and use protected .

Short Answer: Refactor your Packages

Explanation:

The java spec considers the package relationship to be a closer relationship than that of a subclass . This is because I can extend any class as long as I import it.

If you want to be sure the method is not accessible even by subclasses outside the package, use the default visibility modifier.

Source

Stack Overflow reference

To accomplish this, put your class in a package of its own and make methods default protection. There won't be any other classes in the package to see it to call it via package access.

Consider also, that if you seal the jar that the class is in, only you control what is in a given package and have effectively locked any others from creating a class in the package that you define - no one else will be able to introduce a class into the package and break the encapsulation.

Sorry, but protected is your only choice if you want subclasses to be able to call or override a method without making it public . If you do not want other classes in the same package to have access for some reason, move your class to a new package. But if you are thinking that the package and access control keywords form some kind of DRM (ie digital rights management) system rather than simply a code management and class "contract" system, you are mistaken. Think of access control keywords as nothing more than documentation which the compiler has some ability to verify when other code fails to comply with the stated intent as expressed by the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM