Access Modifiers in Java

May 15, 2017

Access Modifiers in Java specifies the level (or scope) of access to classes, variables, methods and constructors. There are four access modifiers in Java:

  1. Private
  2. Protected
  3. Default (no keyword is used)
  4. Public

Public Access Modifier:

Public means available to all. Public classes, methods, variables and constructors are accessible everywhere within the project.

Example:

Let us consider a class – ClassA which has two integer variables – firstNum and secondNum – both defined as public and a method addTwoNumbers(), again defined as public.

Another class with ClassB is defined in which a variable (instance) of ClassA is created and as the variables and methods defined in ClassA are public, all of them are accessible here. Refer below code:

Let us look at another scenario where ClassA is extended by ClassC. Here also all the methods and variables which are public are accessible. Refer below code:

Private Access Modifier:

Private methods and variables can be accessed within same class only. They are not accessible outside the class.

Protected Access Modifier:

Protected methods, variables and constructors can be accessed within the same package via both means (calling from the instance of a class or via Inheritance) but outside a package, they can be accessed only via Inheritance.

Note: Classes cannot be private or protected, they can only be public or default.

Default Access Modifier:

No keyword is used for default access modifier. Methods, variable and constructors can be accessed within the same package only via both ways (creating an instance of a class or via inheritance) but outside a package, it cannot be accessed via any means.

 

 

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: