匿名内部类的使用总结

匿名内部类也就是没有名字的内部类

正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写

但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口

public class innerclassDemo {

	public static void main(String[] args) {
		/**
		 * 1.匿名内部类,用在父类是个抽象类的情况
		 * (1)Person 是一个抽象类 ,直接在实例中定义一个方法say();
		 */
		Person person = new Person() {
			
			@Override
			public void say() {
				System.out.println("hello china!!");
				
			}
		};
		
		person.say();
		
		/**
		 * (2)子类继承Person类,实现say()方法。
		 */
		Person person2 = new Men();
		person2.say();
		
		/**
		 * 2.匿名内部类,用在父类是个接口的情况
		 * (1)InterfacePersonDemo是个接口,直接在实例中定义一个方法eat();
		 */
		InterfacePersonDemo interfacePerson = new InterfacePersonDemo() {
			
			@Override
			public void eat() {
				System.out.println("I like eat bread!!");
				
			}
		};
		
		interfacePerson.eat();
		/**
		 * (2) Woman类实现了InterfacePersonDemo接口,实现内部eat方法。
		 */
		InterfacePersonDemo interfacePerson2 = new Woman();
		interfacePerson2.eat();
		
		
		/**
		 * 3.匿名内部类,用在父类是个可以被继承的情况,父类不能使final的
		 */
		Animal animal = new Animal(){

			@Override
			public void drink() {
				System.out.println("drink a water!");
				
			}
			
			
		};
		animal.drink();
		
		/***
		 * 正常使用
		 */
		Animal animal2 = new Dog();
		animal2.drink();
		
	}

}

//可以被继承的父类
class Animal{
	public void drink() {}
}

//继承父类
class Dog extends Animal{

	@Override
	public void drink() {
		System.out.println("i like water!");
		
	}
	
}


//抽象父类
abstract class Person{
	public abstract void say();
	
}
//继承抽象父类类
class Men extends Person{

	@Override
	public void say() {
		System.out.println("I am a men!!");
		
	}
	
	
}
//接口
interface InterfacePersonDemo{
	public abstract void eat();
	
	
}
//实现接口
class Woman implements InterfacePersonDemo{

	@Override
	public void eat() {
		System.out.println("i eat a bread!");
		
	}
	
}


  

由上面的例子可以看出,只要一个类是抽象的或是一个接口,或者可以被继承且可重写里面方法的父类,那么其子类中的方法都可以使用匿名内部类来实现方法或者创造方法。

最常用的情况就是在多线程的实现上,因为要实现多线程必须继承Thread类或是继承Runnable接口

 

可以参考下面博客:http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html

posted @ 2014-01-20 14:32  侯志凯  阅读(1194)  评论(0编辑  收藏  举报