Java – Access Control

Home/Java - Tutorial/Java - Class/Java – Access Control
Java – Access Control 2017-08-09T10:17:01+00:00

Java Access Control :

One can control what parts of a program can access the member of a class. By controlling access, one can prevent misuse.For Example, allowing access to data only through a well-defined set of methods, one can prevent misuse of that data. Thus, when correctly implemented, a class creates “black box”.

How a member can be accessed is determined by the access specifier that modifies its declaration.

Java provides a set to access specifiers. Some aspects of access control are related to inheritance or packages.

Java’s access specifiers are:

public:

o   When a member of a class is specified by the public specifier, then that member can be accessed by any other code.

o   The public modifier makes a method or variable completely available to all classes.

o   Also when the class is defined as public, it can be accessed by any other class.

private:

o   To hide a method or variable from other classes, private modifier is used.

o    A private variable can be used by methods in it’s own class but not by objects of any other class.

o   Neither private variables nor private methods are inherited by subclass.

o   The only place these variables and methods can be seen is from within their own class.

protected:

o   protected applies only when inheritance is involved.

o   If you want to allow an element to be seen outside your current package, but only to classes that are inherited from your class directly, then declare that element as protected.

default:

o   We have seen that when no access control modifier is specified, it is called as default access.

o   Classes written like this are not accessible in other package.

o   Any variable declared without a modifier can be read or changed by any other class in the same package.

o   Any method declared the same way can be called by any other class in the same package.

o   When a member does not have an explicit access specification,

o    it is visible to subclasses as well as to other classes in the same package.

The following table summarizes the levels of access control.

 

Access

Public

Protected

Default

Private

From the same class

Yes

Yes

Yes

Yes

From any class in the same package

Yes

Yes

Yes

No

From any class outside the package

Yes

No

No

No

From a sub –  class in the same package

Yes

Yes

Yes

No

From a sub –  class outside the same package

Yes

Yes

Yes

No

 

Prev Next