views:

160

answers:

7

Hi, 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 :(.

+6  A: 

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.

Jon Skeet
What's also unexpected for most, is that protected is less restrictive than package/default.
Adriaan Koster
+7  A: 

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.

Richie_W
Although, if we understand "friendly" in the C++ way, that's not exactly the same thing.
Romain
Yes, true - but it seems this scope will suffice as Sergio only wants "it to be accessible only from objects of classes of the same package."
Richie_W
+4  A: 

This is possible by just ommiting public/private in your method declaration. The method is implicitly public, but only accessible within the same package.

Best wishes, Fabian

halfdan
+1  A: 

Just say nothing, default is package visibility.

djna
+1  A: 

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.

FelixM
+2  A: 

Yes - do not put any modifier. Simply

String myString;

Here you can see the semantics of each visibility modifier.

Bozho
A: 

If you don't specify any access modifier then the method will be "package-private" which sounds like it's what you want.

Trevor Tippins