Access modifiers in java (JNNC Technologies)


The access modifiers in java define accessibility (scope) of variable, method, constructor or class.
There are 4 types of access modifiers in java.
  1. Public
  2. Private
  3. Protected
  4. Default
You don’t have to explicitly put default modifier.JVM will use default modifier if you do not provide Public, Private and Protected.

Public access modifier:

Public modifier is accessible in whole java world.If you put class as 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 case of default access modifer, 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.

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();