Access modifiers are keywords in Java that control the visibility and accessibility of classes , methods and constructors and data members.
There are four types of access modifiers in Java
Public – This makes the class, methods , data members accessible from anywhere in the program.
public class MyClass {public void display() {System.out.println("Public method");}}public class MyClass { public void display() { System.out.println("Public method"); } }public class MyClass { public void display() { System.out.println("Public method"); } }
Enter fullscreen mode Exit fullscreen mode
Private -Private keyword makes sure that the data members are only accessible within the same class where they are declared. They are not accessible to other classes even within the same package.
public class MyClass {private int data = 10;private void display() {System.out.println("Private method");}}public class MyClass { private int data = 10; private void display() { System.out.println("Private method"); } }public class MyClass { private int data = 10; private void display() { System.out.println("Private method"); } }
Enter fullscreen mode Exit fullscreen mode
Protected – Protected keyword makes sure that the data members and the methods are accessible within the same package and subclasses.
public class MyClass {protected int data = 10;protected void display() {System.out.println("Protected method");}}public class MyClass { protected int data = 10; protected void display() { System.out.println("Protected method"); } }public class MyClass { protected int data = 10; protected void display() { System.out.println("Protected method"); } }
Enter fullscreen mode Exit fullscreen mode
Default – When none of the keyword is used to define the access of the class, method or data members the default access modifier is applied to it which makes it accessible only within the same package.
class MyClass { // default accessvoid display() { // default accessSystem.out.println("Default method");}}class MyClass { // default access void display() { // default access System.out.println("Default method"); } }class MyClass { // default access void display() { // default access System.out.println("Default method"); } }
Enter fullscreen mode Exit fullscreen mode
Thanks for reading , try simplifying more in the comments and help others :>
暂无评论内容