In this tutorial, we will learn about the Access Modifiers in Java, or its types, and how to use them with the help of examples.
What is a Access Modifiers in Java
This modifier specifies the scope of a field, method, constructor, or class. We can change access level of field, constructor, method, and class by applying the access modifier on it.
There are four types of Access Modifier
- Private Access Modifier
- Public Access Modifier
- Protected Access Modifier
- Default Access Modifier
Private
The Private access level of a private modifier is only within the class. It cannot be access from outside the class.
Example
Private Access Modifierclass Royal { private String name; public String getName() { return this.name; } public void setName(String name) { this.name= name; } } public class Accessesdpps { public static void main(String[] main){ Royal d = new Royal(); d.setName("Basic Engineer"); System.out.println(d.getName()); } }
Let’s run the code
Public
The Public access level of a public modifier is everywhere. Its means, can be access from within the class, outside the class, within the package and outside the package.
Example
Public Access Modifierpublic class A{ protected void msg(){System.out.println("Basic engineer");} }
Let’s run the code
Public Access Modifierclass B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } }
Let’s run the code
Protected
The Protected access level of a protected modifier is within the package and outside the package through child class is knows as Protected Access.
Example
Protected Access Modifierpublic class AccessA{ protected void msg(){System.out.println("Basic Engineer");} }
Let’s run the code
Protected Access Modifierclass AccessB extends AccessA{ public static void main(String args[]){ AccessB obj = new AccessB(); obj.msg(); } }
Let’s run the code
Output Value
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about JAVA Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments