1. 程式人生 > >java中內部類的建立四種情況,三種方式,及內部資料訪問許可權

java中內部類的建立四種情況,三種方式,及內部資料訪問許可權

內部類和外部類的關係,及內部靜態類的資料訪問許可權,宣告方式。

第一種,在外部類內部宣告使用內部類,內部類的型別為static和非 static型別,內部類資料型別為private,protected,public 型別的訪問許可權。外部類為非靜態宣告和許可權如下:

package com;

public class Test1 {
	//@author 張春蕾
	private class Name{
		private int i =1;
		public int s = 2;
		protected int m =3;
	}
	public static void main(String[] args){
		Test1 test = new Test1();
		<span style="color:#ff0000;">Test1.Name name = test.new Name();
		System.out.print(name.i);</span>
		System.out.print(name.s);
		System.out.print(name.m);
	}
}
宣告方式,而且所有的內部引數不論什麼都可以輸出。當內部類為靜態類時,宣告方式會發生變化:
package com;

public class Test1 {
	//@author 張春蕾
	private static class Name{
		private int i =1;
		public int s = 2;
		protected int m =3;
	}
	public static void main(String[] args){
		Test1 test = new Test1();
		<span style="color:#ff0000;">Test1.Name name = new Name();</span>
		System.out.print(name.i);
		System.out.print(name.s);
		System.out.print(name.m);
	}
}
上面的方式都是在Test1的內部進行訪問,現在外部的Test2力訪問情況為第二種,當內部類為非靜態的時候的宣告方式:
package com;

public class Test1 {
	//@author 張春蕾
	<span style="color:#33cc00;">protected</span> class Name{
		private int i =1;
		public int s = 2;
		protected int m =3;
	}
	public static void main(String[] args){
		Test2 t = new Test2();
		t.test();
	}
}
class Test2{
	public void test(){
		<span style="color:#009900;">Test1 test = new Test1();
		Test1.Name name = test.new Name();//跟第一種情況一樣
		System.out.println(name.m);
		System.out.print(name.s);</span>
	}
}

</pre><p></p><pre>
跟第一種的非靜態內部類的宣告方式相同,不過不能訪問內部靜態變數,當內部類為靜態時,訪問形式:
package com;

public class Test1 {
	//@author 春蕾
	<span style="color:#33cc00;">protected</span> static class Name{
		private int i =1;
		public int s = 2;
		protected int m =3;
	}
	public static void main(String[] args){
		Test2 test2 = new Test2();
		test2.test();
	}
}
class Test2{
	public void test(){
		<span style="color:#009900;">Test1.Name name2 = new Test1.Name();
		System.out.print(name2.m);
		System.out.print(name2.s);</span>
	}
}