elibraryportal Logo

Access Modifiers in Java

→ Access modifiers are used to set the accessibility of classes, interfaces, variables, methods, constructors, data members, and the setter methods.

Types of Access Modifiers

There are two types of access modifiers

Access Modifiers in Java

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.

Access Modifierwithin classwithin packageoutside package by subclass onlyoutside package
PublicYYYY
PrivateYNNN
ProtectedYYYN
DefaultYYNN

1) public access modifier

→ The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example :-


Output

public access modifier Example

2) Private access modifier

→ Private access modifier they cannot be accessed outside of the class When declared variables and methods are private .

→ The private access modifier is accessible only within class.

Example :-

Compile time Error

Output

Private access modifier Example

3) Protected access modifier

→ Protected Access Modifier can access within the same package as well as from subclasses, when methods and data members are declared protected

→ Protected Access Modifier can be applied on the data member, method and constructor. It can't be applied on the class.

Example 1 :-

Output

Protected access modifier Example

Example 2 :-

Output

Protected access modifier Example

4) Default access modifier

→ If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package.

Example :-

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.