《一》定义:匿名内部类也就是没有名字的内部类;匿名内部类只能使用一次,它通常用来简化代码编写;
《二》前提条件:使用匿名内部类必须继承一个父类或实现一个接口;只要一个类是抽象的或是一个接口,那么其子类中的方法都可以使用匿名内部类来实现;
接口:
interface dag{ public void eat(); } public class forNBclass { public static void main(String[] args) { dag dag1 = new dag() { @Override //——————————匿名内部类 public void eat() { System.out.println("eat bone!"); } }; dag1.eat(); } }
抽象类:
abstract class dag { public abstract void eat(); } public class forNBclass { public static void main(String[] args) { dag d1 =new dag() { @Override //——————————匿名内部类 public void eat() { System.out.println("12"); } }; d1.eat(); } }
Thread类的匿名内部类实现:
public class forNBclass { public static void main(String[] args) { Thread th1 =new Thread(){ public void run(){ for (int i = 1; i <8; i++) { for (int j = 1; j <=i ; j++) { System.out.print(i+" * "+j+" = "+j*i+" "); } System.out.println(); } } }; th1.start(); } }
Runnable接口的匿名内部类实现:
public class forNBclass { public static void main(String[] args) { Runnable R1 =new Runnable() { @Override public void run() { for (int i = 1; i <8; i++) { for (int j = 1; j <=i ; j++) { System.out.print(i+" * "+j+" = "+j*i+" "); } System.out.println(); } } }; Thread th1 = new Thread(R1); th1.start(); } }