Loading

Java访问权限

public > protected > default > private

  • public:该成员可以被任意包下,任意类的成员进行访问;
  • protected:该成员可以被该类内部成员访问,也可以被同一包下其他的类访问,还可以被它的子类访问;
  • defalut:该成员可以被该类内部成员访问,也可以被同一包下其他的类访问;
  • private:该成员可以被该类内部成员访问。
访问权限 本类 本包的类 本包的子类 外包的子类 外包的类
public
protected
default
private

上代码:Java访问权限.zip

//文件结构
Test
|-- src
   |-- cat --------猫猫包
      |-- Kit -----本包的子类
      |-- Kitt ----本包的类
      |-- Kitty ---本类
   |-- dog --------狗狗包
      |-- Ki ------外包的子类
      |-- Puppy ---外包的类

本类

// 本类
package cat;

public class Kitty {
    public static String catA = "catA";
    protected static String catB = "catB";
    static String catC = "catC";
    private static String catD = "catD";

    public static void main(String[] args) {
        // OK
        System.out.println(catA);
        // OK
        System.out.println(catB);
        // OK
        System.out.println(catC);
        // OK
        System.out.println(catD);
    }
}

本包的类

// 本包的类
package cat;

public class Kitt {
    public static void main(String[] args) {
        // OK
        System.out.println(Kitty.catA);
        // OK
        System.out.println(Kitty.catB);
        // OK
        System.out.println(Kitty.catC);
        // ERROR, 'catD' has private access in 'cat.Kitty'
        System.out.println(Kitty.catD);
    }
}

本包的子类

// 本包的子类
package cat;

public class Kit extends Kitty {
    public static void main(String[] args) {
        // OK
        System.out.println(catA);
        // OK
        System.out.println(catB);
        // OK
        System.out.println(catC);
        // ERROR, 'catD' has private access in 'cat.Kitty'
        System.out.println(catD);
    }
}

外包的子类

// 外包的子类
package dog;

import cat.Kitty;

public class Ki extends Kitty {
    public static void main(String[] args) {
        // OK
        System.out.println(catA);
        // OK
        System.out.println(catB);
        // ERROR, 'catC' is not public in 'cat.Kitty'. Cannot be accessed from outside package
        System.out.println(catC);
        // ERROR, 'catD' has private access in 'cat.Kitty'
        System.out.println(catD);
    }
}

外包的类

// 外包的类
package dog;

import cat.Kitty;

public class Puppy {
    public static void main(String[] args) {
        // OK
        System.out.println(Kitty.catA);
        // ERROR, 'catB' has protected access in 'cat.Kitty'
        System.out.println(Kitty.catB);
        // ERROR, 'catC' is not public in 'cat.Kitty'. Cannot be accessed from outside package
        System.out.println(Kitty.catC);
        // ERROR, 'catD' has private access in 'cat.Kitty'
        System.out.println(Kitty.catD);
    }
}

逐行注释,基本上也没啥好解释的

posted @ 2021-11-01 17:18  菜月昴  阅读(38)  评论(0编辑  收藏  举报