Java Access Modifiers – Public, Private, Protected, Friendly

Java Access Modifiers:

In Java, We have seen that the variables and methods of a class are visible everywhere in the program. However, it may be necessary in some situations to restrict access to certain variables and methods from outside the class. We can achieve this in Java by applying visibility modifiers to the instance variables and methods. These visibility modifiers are also known as Java Access Modifiers. There are five types of Java Access Modifiers are exists:

  • Public Access Modifiers
  • Private Access Modifiers
  • Friendly or Default Access Modifiers
  • Protected Access Modifiers
  • Private Protected Access Modifiers

Public:

Any variable or method is visible to the entire class in which it is defined. A variable or method declared as public has the widest possible visibility and is accessible everywhere.
Example:

public int number;
public void add()
{
.........
.........
}

Private:

The private field has the highest degree of protection. They are accessible only to their class. They can’t be inherited by subclasses and therefore not accessible in the subclass. A method declared as private behaves like a method declared as final. It prevents the method from being subclassed.
Example:

private int number;
private void add()
{
.........
.........
}

Friendly or Default:

When no access modifier is specified, the member defaults to a limited version of public accessibility that is known as “Friendly or Default Access Modifiers”.

The difference between the “public” and “friendly or default” access modifiers is that the public makes fields visible in all classes including other packages, while friendly or default makes fields visible only in the same package, but not in other packages.

Example:

int number;
void add()
{
.........
.........
}

Protected:

The protected makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages and non-subclasses in other packages can’t access the protected members.
Example:

public class test{
protected int number;
protected void add()
{
.........
.........
}
}

Private Protected:

Private Protected makes the fields visible in all subclasses regardless of what package they are in. These fields aren’t accessible by other classes in the same package.

Example:

private protected int number;
private protected void add()
{
.........
.........
}