public

Public means that anyone can access and use the element;

public class Test {
    public static void main(String[] args) {
        Person p=new Person();
        System.out.println(p.name);// Output Xiao Ming}}class Person{
   public String name="Xiao Ming";
}
Copy the code

At this point we can access the name directly through the Person object P.

private

The element is not directly accessible to outsiders except for the class itself and methods inside the class.

public class Test {
    public static void main(String[] args) {
        Person p=new Person();
        System.out.println(p.name);// The name cannot be accessed directly}}class Person{
   private String name="Xiao Ming";
}
Copy the code

protected

Protected is similar to private, except that subclasses can access protected members but not private members.

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        System.out.println(student.name);// Name cannot be accessed
        System.out.println(student.age);// But you can access age}}class Person{
   private String name="Xiao Ming";
   protected String age="10";
}
class Student extends Person{}Copy the code

default

If you do not use the first three, the default is default access. Default is called package access because resources under this permission can be accessed by members of other classes in the same package (library components).

summary