javaSE基础-内部类

package com.zy.jczyw.testcase;

class Outer{

	private int x = 3;

	class Inner{
		int x = 4;
		void function (){
			int x = 5;
			System.out.println(x); //5
			System.out.println(this.x);  //4
			System.out.println(Outer.this.x); //3
		}
	}


	void method(){
			Inner in = new Inner();
			in.function();
	}
}

public class InnerDemo{
	public static void main(String[] args) {
		Outer out = new Outer();
		out.method();
		
		Outer.Inner inner = new Outer().new Inner();
		inner.function();
	}
}

内部类访问规则:
1,内部类可以直接访问外部类中的成员,包括私有,原因:内部类中持有一个外部类的引用,格式:外部类名.this
2,外部类要访问内部类,必须建立内部类对象
在这里插入图片描述
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章