Saturday, September 17, 2011

Access Modifier

Protected members of class:

may be directly accessed by methods of the same class or methods of a subclass. Protected members may be accessed by methods of any class that are in the same package.

Java provides a third access specification, protected.

A protected member’s access is somewhere between private and public.

Using protected instead of private makes some tasks easier.

However, any class that is derived from the class, or is in the same package, has unrestricted access to the protected member.

It is always better to make all fields private and then provide public methods for accessing those fields.

If no access specifier for a class member is provided, the class member is given package access by default.

Any method in the same package may access the member.

Access Modifier

Accessible to a subclass inside the same package?

Accessible to all other classes inside the same package?

default
(no modifier)

Yes

Yes

Public

Yes

Yes

Protected

Yes

Yes

Private

No

No

Access Modifier

Accessible to a subclass outside the package?

Accessible to all other classes outside the package?

default
(no modifier)

No

No

Public

Yes

Yes

Protected

Yes

No

Private

No

No

Default modifier = package?

No comments:

Post a Comment