Java内部类(三)匿名内部类

如果只需要创建一个内部类的一个对象,就没必要给这个类一个名字。这个没有名字的内部类叫做匿名内部类。

1. 扩展自接口的匿名内部类

package innerclass;

public interface Say {
	public void saySomething();
}

package innerclass;

public class TestSay {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Say say = new Say() {

			@Override
			public void saySomething() {
				// TODO Auto-generated method stub
				System.out.println("I LOVE YOU");

			}
		};
		say.saySomething();
	}

}

运行结果:

I LOVE YOU


2.扩展自类的匿名内部类

package innerclass;

public class Said {
	public void saidSomething() {
		System.out.println("I LOVED YOU");
	}
}

package innerclass;

public class TestSaid {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Said said = new Said(){
			public void saidSomething() {
				System.out.println("I DON'T LOVE YOU NOW");
			}
		};
		said.saidSomething();

	}
	

}

运行结果:

I DON'T LOVE YOU NOW

你可能感兴趣的:(java,匿名内部类)