Sergio A.
Sergio A.

Reputation: 33

Is there a way to declare a method "friendly" in Java?

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

Upvotes: 3

Views: 8860

Answers (7)

halfdan
halfdan

Reputation: 34204

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

Upvotes: 4

Richard Walton
Richard Walton

Reputation: 4785

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.

Upvotes: 8

Trevor Tippins
Trevor Tippins

Reputation: 2847

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

Upvotes: 0

Bozho
Bozho

Reputation: 597016

Yes - do not put any modifier. Simply

String myString;

Here you can see the semantics of each visibility modifier.

Upvotes: 2

FelixM
FelixM

Reputation: 1506

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.

Upvotes: 1

djna
djna

Reputation: 55897

Just say nothing, default is package visibility.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 8

Related Questions