What are access modifiers in Java?

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 access
void display() { // default access
System.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 :>

原文链接:What are access modifiers in Java?

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
Little compliments mean so much to me sometimes.
有时候,一点微不足道的肯定,对我却意义非凡
评论 抢沙发

请登录后发表评论

    暂无评论内容