Java 嵌套类和内部类演示样例<三>

<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:18px;">package nested_inner_class;</span></span>
<span style="font-size:18px;">
public class StaticNestedTest3 {

	public static void main(String[] args) {
		//奇特的内部类实例化方法
		Outer3 outer3 = new Outer3();
		Outer3.Nested nested = outer3.new Nested();
		//使用下面方法无法创建。下面方法仅仅能创建静态嵌套类
		//Outer3.Nested nested = new Outer3.Nested();
		
		System.out.println(nested.getValue());
		System.out.println(nested.getOuterValue());
	}

}

class Outer3{
	private int value = 9;
	//非静态的嵌套类(也可称为成员内部类)(Nested1)能够訪问外层类(Outer)的全部(包含private)成员
	//能够把嵌套类当做外部类的一个函数来理解(为什么能够訪问外部类的成员)
	 class Nested{
		
		int value = 10;
		
		/*
		 *  Note:
		 *  内部类中引用当前实例(内部类的实例)用 this
		 *  内部类中引用外层类实例用 Outer3.class,这和引用外层类的静态变量不同
		 * */
		
		
		//返回内部类的value
		int getValue(){
			return this.value;
		}
		
		//返回外部类的value
		int getOuterValue(){
			//内部类訪问外部类对象的奇特方法
			return Outer3.this.value;
		}
	}
}</span>

嵌套类(nested class)是一个在还有一个类或接口内部声明的类。

嵌套类分为两种:静态内部类(static inner class)和非静态嵌套类(non-static nested class)。非静态嵌套类也称为内部类(inner class)

原文地址:https://www.cnblogs.com/zhchoutai/p/6943750.html