• 内部类


    /*
    内部类的访问规则:
    1、内部类可以直接访问外部类的成员,包括私有成员,之所以可以直接访问外部类成员,是因为内部类中持有一个外部类的引用,格式:外部类名称.this
    2、外部类要访问内部类,必须要建立内部类对象
    	一般我们都将内部类私有化进行封装起来。
    访问格式:
    当内部类定义在外部类的成员位置时,而且是非私有,可以再外部其他类中直接建立内部类对象。
    格式:
    	外部类名.内部类名   变量名 = 外部类对象.内部类对象;
    	Outer.Inner in=new Outer().new Inner();
    2、当内部类在成员变量位置上时可以被成员变量修饰符修饰,比如,private:将内部类在外部类中进行封装,static:内部类就具有static特性。
    	当内部类被static修饰后,只能直接访问外部类中的静态成员,出现访问局限,
    
    	在外部其他类中,如何直接访问static内部类的非静态成员呢?
    	new Outer.Inner().funtion();
    
    	在外部其他类中,如何直接访问static内部类的静态成员呢?
    	Outer.Inner.function();
    	注意:当内部类中定义了静态成员,该内部类必须是静态类。
    	当外部静态方法访问内部类时,内部类必须为惊天。
    */
    
    class Outer
    {
    	private int x = 3;
    	class Inner
    	{
    		int x=4;
    		void function()
    		{
    			int x=7;
    			System.out.println(x);					//输出7
    			System.out.println(this.x);				//输出4
    			System.out.println(Outer.this.x);		//输出3
    							    //上面定义的三个变量x,是种特殊情况,一般如果没有this类的指定修饰,直接输出x。采取的就近原则
        <span style="white-space:pre">	</span>						   //注释int x=7,那么println(x)和println(this.x)是一样的												  //注释int x=4,那么println(this.x)是错误的,因为内部类没有成员x
    		}
    	}
    
    	static class Inner2
    	{
    		static int y=10;
    		void function()
    		{
    			System.out.println("静态内部类。");
    		}
    	}
    
    	void method()									//外部类成员访问内部类
    	{
    		Inner in=new Inner();
    		in.function();
    	}
    }
    class InnerDemo 
    {
    	public static void main(String[] args) 
    	{
    		Outer outer=new Outer();
    		outer.method();					//访问外部类中成员
    
    		Outer.Inner in=new Outer().new Inner();			//创建内部类对象
    		in.function();
    
    		System.out.println(Outer.Inner2.y);             //访问静态内部类中的静态成员
    		new Outer.Inner2().function();					//访问静态类中的非静态成员.
    	}
    }
    

  • 相关阅读:
    STM8S PWM输出停止后 IO口电平输出
    STM8 输出比较极性
    无法打开包括文件: “corecrt.h”: No such file or directory
    VC++深入详解学习笔记
    x86系列微处理器中8种描述符表https://blog.csdn.net/u014162133/article/details/46573873
    计算机目录
    windbg双机调试
    二叉树
    list
    vector
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258561.html
Copyright © 2020-2023  润新知