修飾符 | 類內部 | 同一個包 | 子類 | 任何地方 |
private | yes | |||
package | yes | yes | ||
protected | yes | yes | yes | |
public | yes | yes | yes | yes |
權限修飾符主要用來修飾成員變量、方法和類;而類只能用public和package(默認什麼修飾詞都不寫)這兩種權限來限定訪問。說得通俗些,權限修飾符就是用於指定成員變量、方法和類的訪問權限的。java
一、修飾成員變量和方法:spa
注:pak1包下有Person和Student兩個類;pak2包下有Student類code
package pak1; public class Person { private int i = 0; int j = 0; protected int k = 0; public int m = 0; public void pub() { System.out.println(i); System.out.println(j); System.out.println(k); System.out.println(m); } private void pri() { System.out.println("private"); } protected void pro() { System.out.println("protected"); } void def() { System.out.println("default"); } }
package pak1; public class Student { public void m() { Person p = new Person(); System.out.println(p.i); //報錯,i爲private System.out.println(p.j); System.out.println(p.k); System.out.println(p.m); p.pri(); //報錯,pri()爲private p.def(); p.pro(); p.pub(); } }
package pak2; import pak1.Person; public class Student { //這裏Student類並未繼承Person類 public void m() { Person p = new Person(); System.out.println(p.i); //報錯 i爲private System.out.println(p.j); //報錯 j爲package System.out.println(p.k); //報錯 k爲protected,Student非同包,非子類 System.out.println(p.m); p.pri(); //報錯 pri()爲private p.def(); //報錯 def()爲package p.pro(); //報錯 pro()爲protected,Student非同包,非子類 p.pub(); } }
package pak2; import pak1.Person; public class Student extends Person { //這裏Student繼承了Person父類 public void m() { Person p = new Person(); Student s = new Student(); System.out.println(p.i); //報錯 System.out.println(p.j); //報錯 System.out.println(p.k); //報錯:在子類中經過父類對象引用不能訪問父類中用protected修飾的k System.out.println(p.m); System.out.println(s.i); //報錯 System.out.println(s.j); //報錯 System.out.println(s.k); //注意:在子類中經過子類對象引用則能訪問父類中用protected修飾的k System.out.println(s.m); System.out.println(i); //報錯 System.out.println(j); //報錯 System.out.println(k); //注意:在子類中能直接訪問父類中用protected修飾的k System.out.println(m); p.pri(); //報錯 p.def(); //報錯 p.pro(); //報錯:在子類中經過父類對象引用不能訪問父類中用protected修飾的pro() p.pub(); s.pri(); //報錯 s.def(); //報錯 s.pro(); //注意:在子類中經過子類對象引用則能訪問父類中用protected修飾的pro() s.pub(); pri(); //報錯 def(); //報錯 pro(); //注意:在子類中能直接訪問父類中用protected修飾的pro() pub(); } }
固然,權限修飾符也能夠用來修飾某類的構造方法,效果等同普通方法。對象
二、修飾類(public或package修飾外部類,可用全部權限修飾內部類):繼承
使用包權限修飾的外部類不能被導入(import)。ci
注:pak1包下有Animal和Cat兩個類;pak2包下有Cat類table
package pak1; class Animal { //用包權限修飾Animal類 public void speak() { System.out.println("wangwangwang~miaomiao"); } }
package pak1; public class Cat { public void m() { Animal a = new Animal(); a.speak(); } }
package pak2; import pak1.Animal; //報錯,用包權限修飾的Animal類不能被導入 import pak1.*; public class Cat { Animal a = new Animal(); //報錯,因爲用包權限修飾的Animal類不能被導入,因此不能建立此類對象 }