瞭解了包的概念,就能夠系統的介紹Java中的訪問控制級別。在Java中,針對類、成員方法和屬性提供了四種訪問級別,分別是private、default、protected和public。html
public(公共) | protected(受保護) | default(缺省) | private(私有) | |
同一個類 | √ | √ | √ | √ |
同一個包 | √ | √ | √ | × |
子父類 | √ | √ | × | × |
不一樣包 | √ | × | × | × |
package d; class Demo7 { protected int a = 1 ; }
package d; public class Demo8 { public static void main(String[] args) { Demo7 z = new Demo7(); System.out.println("a="+z.a); } }運行結果:
package d; class Demo7 { int a = 1 ; }
package d; public class Demo8 { public static void main(String[] args) { Demo7 z = new Demo7(); System.out.println("a="+z.a); } }運行結果:
package d; class Demo7 { protected int a = 1 ; }
package d; public class Demo8 extends Demo7 { public static void main(String[] args) { Demo8 z = new Demo8(); System.out.println("a="+z.a); } }運行結果:
package d; class Demo7 { int a = 1 ; }
package e; import d.*; public class Demo8 extends Demo7 { public static void main(String[] args) { Demo8 z = new Demo8(); System.out.println("a="+z.a); } }運行結果:
package d; class Demo7 { protected int a = 1 ; }
package e; import d.*; public class Demo8{ public static void main(String[] args) { Demo7 z = new Demo7(); System.out.println("a="+z.a); } }運行結果:
package d; class Demo7 { int a = 1 ; }
package e; import d.*; public class Demo8{ public static void main(String[] args) { Demo7 z = new Demo7(); System.out.println("a="+z.a); } }運行結果: