java匿名内部类

*A:匿名内部类
 * 就是局部内部类的简化写法。
* B:前提:存在一个类或者接口
 * 这里的类可以是具体类也可以是抽象类。
* C:格式:
*
  new 类名或者接口名(){
   重写方法;
  }
* D:本质是什么呢?
 * 是一个继承了该类或者实现了该接口的子类匿名对象。

interface Inter
{
	void show();
}
class Outer
{
	private int num=10;
	//局部内部类的写法
	/*class Inner implements Inter 
	{
		public void show(){
		System.out.println("show");
		}
	}*/
	public void method(){
		
		//Inner inn=new Inner();
		//new Inter (){};  定义实现类,重现接口方法,然后实例化对象,实现对象
		Inter inn=new Inter(){
			public void show(){
				//重写方法
			System.out.println("no name inner class show");
			}
		};
		inn.show();
	}
}


class Demo_NonameInner {
	public static void main(String[] args) {
		Outer out=new Outer();
		out.method();
		System.out.println("Hello World!");
	}
}

代码2:

interface  Inter
{
	void show1();
	void show2();
}
class Outer
{
	private int num=10;
	public void method(){
		//如果匿名内部类重写多个方法,用基类引用接受对象
		/*Inter in=new Inter(){
		public void show1(){
			System.out.println("show1");
		}
		public void show2(){
			System.out.println("show2");
		}
		};
		in.show1();
		in.show2();
	}*/
	//匿名内部类只有一个方法用标准写法
	new Inter(){
		public void show1(){
			System.out.println("show1");
		}
		public void show2(){
			System.out.println("show2");
		}
	}.show2();
	
	}
}
class  Demo2_NonameInner{
	public static void main(String[] args) {
		Outer out=new Outer();
		out.method();
		System.out.println("Hello World!");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38763885/article/details/80666219