问题
I know that attributes can be set public, friendly or private to specify its visibility.
Is there a way I can declare a friendly method? I want it to be accessible only from objects of classes of the same package.
Thanks you, a beginner here :(.
回答1:
By not entering a visiblity modifier Java uses the package private scope
Check out the following article
Edit: As mentioned in the comments, there is no way to mark a method as "friendly". But for your needs, package-private will suffice.
回答2:
Just don't specify the accessibility - that defaults to "package visible" or "default access". Unfortunately there's no way of doing this explicitly.
Note that protected access is not only related by inheritance, but also includes other types in the same package. (This has always seemed slightly odd to me, but never mind.)
See the Java Language Specification section 6.6 for details.
回答3:
This is possible by just ommiting public/private in your method declaration. The method is implicitly public, but only accessible within the same package.
回答4:
Yes - do not put any modifier. Simply
String myString;
Here you can see the semantics of each visibility modifier.
回答5:
Just say nothing, default is package visibility.
回答6:
In Java you have public, protected, package and private visibility. Package visibility is also known as default since you specify it by leaving out the other keywords.
回答7:
If you don't specify any access modifier then the method will be "package-private" which sounds like it's what you want.
来源:https://stackoverflow.com/questions/1839365/is-there-a-way-to-declare-a-method-friendly-in-java