Summary table for Java access specifiers

Summary table for Java access specifiers

Summary table for Java access specifiers

Summary table for Java access specifiers

Visibility

Private

Default

Protected

Public

Within the same class

Yes

Yes

Yes

Yes

From child class of the same package

No

Yes

Yes

Yes

From a non-child class of the same package

No

Yes

Yes

Yes

From child class of outside package

No

No

Yes(We should use child class reference only)

Yes

From a non-child class of outside package

No

No

No

Yes

 

Access specifiers are used to restricting access in programming. These specifiers determine whether a field or method in a class can be used or invoked by another class method or subclass method. There are four access specifiers

  1. Public
  2. Private
  3. Protected
  4. Default

These are used according to our specification to access in certain levels in programming.

1) public Classes, methods, and fields which are declared as public can be accessed from any other class in the Java program, whether they are in the same package or in another package.

2)private fields and methods which declared as private can be accessed within the same class to which they belong. Using private specifier we can also achieve encapsulation which is used for hiding data

3) protected fields and methods which declared as protected can only be accessed by subclasses in another package or any class within the package of protected members class. Remember, the protected specifier is not applied to class and interfaces.

4) default if you don’t declare any specifier, it will follow the default accessibility level. where there is No default keyword. Classes, fields, methods can be a default (no declaration of specific) accessed. By using default specifier we can access class, method, or field which belongs to the same package, but not from outside this package.

  • The most restricted modifier is private.
  • The most accessible modifier is public.
  • Private<default<Protected<Public.
  • Recommended modifier for date member(variable) is private.
  • Recommended modifier for the method is public.

Leave a Reply

Your email address will not be published. Required fields are marked *

*