JAVA學習之內部類(一)
阿新 • • 發佈:2019-02-03
/* 內部類的訪問規則: 1.內部類可以直接訪問外部類中的成員,包括私有成員; 是因為內部類中持有了一個外部類的引用,格式:外部類名.this 2.外部類要訪問內部類,必須建立內部類物件。 */ class Outer { private int x = 3; class Inner //內部類,可以被private修飾,修飾後,在第33行將出現錯誤,無法訪問到private成員。 { //int x = 4; void function() { //int x = 5; System.out.println("Inner:"+x); //隱藏了Outer.this.x;x=5,this.x=4,Outer.this.x=3。 } } void method() { Inner in = new Inner(); in.function(); System.out.println("Outer:"+x); } } class InnerclassDemo { public static void main(String[] args) { //Outer out = new Outer(); //out.method(); Outer.Inner inner = new Outer().new Inner(); inner.function(); } }