« Home | Why refactoring helps? » | No New Year Resolutions for Me » | Learning Tips » | IIM CAT 2004 - The wounded lion roars back » | Personality Types » | Is Xtreme Programming the next Strategic Inflectio... » | I "WILL" » | Reading Better and Faster » | I am blogging »

Java and Access Specifiers

So many times there is confusion about java and its access specifers. Here’s what they mean once and for all.

Public: Available to all wherever you may be.

Private: Available only to me.

Protected: Available to my derived types.

Friend: Available to all who belong to my group (package) i.e. are my friends.

Naturally, if I make a class private it can’t be accessed by anyone except the class itself! Now trying make a class protected. Then it will available to only its derived types. But its protected and you cant derive a type. Hence classes don’t have private/protected specifiers. They have only public / friend specifiers.

However pick any class member and you can safely say it can be either public, private, protected or friend.

That’s good enough. But real java code will be a mix of public/friend classes with members at different access levels. The matrix is revealed below:

The following is a list of classes we have:

Class

Access

Package

A

Public

com.test

B

Public or Friend

com.test

C extends A

Public of Friend

com.test

D

Public of Friend

com.testother

E extends A

Public of Friend

com.testother

Lets see what members of A are accessible to what members of B, C, D, E. Classes B, C are in same package as A while D, E are outside of the package that A belongs to.

Non static members of A

Can be accessed by

Can be overridden by

Public

B, C, D, E

C, E

Protected

C, E

C, E

Friend

B, C

C

Private

None

None

Now lets apply the above to a friend class.

The following is a list of classes we have:

Class

Access

Package

F

Friend

com.test

G

Public or Friend

com.test

H extends F

Public of Friend

com.test

Naturally here I consider classes only in same package as F.

Lets see what happens here.

Non static members of F

Can be accessed by

Can be overridden by

Public

G, H

H

Protected

H

H

Friend

G, H

H

Private

None

None

Note that static public members of F can be accessed outside the package !