• 【java】内部类


    内部类:将一个类定义在另一个类里。对里面的那个类就是内部类。

    访问特点:

    1.内部类可以直接访问外部类的成员,包括私有。之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部的引用,格式 外部类名.this
     外部类要访问内部类,必须建立内部类对象。

    2.当内部类定义在外部类的成员位置上,而且为非私有,可以在外部类或者外部其他类中直接建立内部类对象。
    格式为:外部类名.内部类名 变量名 = 外部类对象。内部类对象;
        Outer.Inter i1=new Outer().new Inter();

    3.当内部类在成员位置上,就可以被成员修饰符修饰。
           比如private:将内部类在外部类中进行封装
        static:内部就具备了static的特性.
     当内部类被static修饰后,只能直接访问外部类的static成员,出现了访问的局限性。
       在外部其他类中,如何直接访问static内部类的非静态成员?
        new Outer.Inter().function();
      在外部其他类中,如何直接访问static内部类的静态成员?
        Outer.Inter.function();
    4.当内部类定义了静态成员,该内部类必须是static的。当外部类的静态方法访问内部类时,内部类也必须是static的。

    class Outer
    {
    	private int x=1;
    	private int num=3;
    	class Inter//内部类
    	{
    		int x=4;
    		void function()
    		{
    			int x=6;
    			System.out.println("i am  inter : "+num);
    			System.out.println("inter x1 : "+Outer.this.x);//外部类名.this方式直接访问外部类成员
    			System.out.println("inter x2 : "+this.x);//访问内部类成员
    			Outer.this.show();//外部类名.this方式直接访问外部类成员
    		}
    	}
    
    	void show()
    	{
    		System.out.println(num);
    	}
    }
    
    
    class  InterDemo
    {
    	public static void main(String[] args) 
    	{
    		Outer o1=new Outer();
    		o1.show();
    		Outer.Inter i1=new Outer().new Inter();//外部类要访问内部类,必须建立内部类对象。
    		i1.function();
    	}
    }
    

     

    匿名内部类:
    1.匿名内部类实际就是内部类的简写格式。
    2.定义匿名内部类的前提:
      内部类必须是继承一个类或者实现接口
    3.匿名内部类的格式:
      new 父类或者接口(){定义子类的内容}
    4.其实匿名内部类就是一个匿名子类对象。可以理解为带内容的对象
    5.匿名内部类中定义的方法最好不要超过3个

    interface Inter
    {
    	void show(int a,int b);
    	void func();
    }
    class Demo
    {
    	public static void main(String[] args)
    	{
    		//补足代码;调用两个函数,要求用匿名内部类
    		Inter in = new Inter()
    		{
    			public void show(int a,int b)
    			{
    			
    			}
    			public void func()
    			{
    			
    			}
    		};
    
    		in.show(4,5);
    		in.func();
    		
    	}
    }
    

      

  • 相关阅读:
    Qt之使用CQU库快速开发统一风格界面
    Springboot中使用redis进行api防刷限流
    SpringBoot使用拦截器、过滤器、监听器
    ElasticSearch中文分词器-IK分词器的使用
    里式替换原则——面向对象程序设计原则
    使用Spring中的PropertyPlaceholderConfigurer读取文件
    新版本SpringCloud sleuth整合zipkin
    解放双手,在PC端进行Android真机调试
    破解Android设备无法联调的谜题
    打python&adb组合拳,实现微信读书永久免费读
  • 原文地址:https://www.cnblogs.com/paulwinflo/p/8042448.html
Copyright © 2020-2023  润新知