Access modifiers in java

The access modifiers in java define accessibility (scope) of variable, method, constructor or class.
There are 4 types of access modifiers in java.

You don’t have to explicitly put the default modifier.JVM will use default modifier if you do not provide Public, Private and Protected.

Public access modifier

Public modifier is accessible in the whole java world. If you put class as the public that means that class is available everywhere.

Let’s see with help of example:
Create a class named A.java in package com.

Create another class named "B.java" in package com.

When you run above program, you will get below output:

In method of class A
Value of variable a is: 20

Private access modifier

The private access modifier is accessible only within class.
You can not use private and protected with class unless and until it is nested class.
Let’s understand it with the help of example:

You will get compilation error at line no.22 and 23, as you can not access private variables or methods from outside the class.

Default access modifier

If you do not provide any access, JVM considers it as default access. In the case of default access modifier, you can not access method, variable or class outside of the package.
Create a class named A.java in package com.

Create another class named "B.java" in package com.

Here you will get compilation error at line no.11 and 12,as we are trying accesss variable a and methodA of class A outside the package com

Protected access modifier

Protected access modifiers can be accessed within the same package or outside the package by inheritance only.
Let’s understand with the help of example:
Create a class named A.java in package com.

Create another class named "B.java" in package com.

When you run above program, you will get below output:

In method of class A
Value of variable a is: 20

As you can see, we are able to access class A’s variable a and methodA using inheritance.

That’s all about access modifiers in Java.

Was this post helpful?

Leave a Reply

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