匿名内部类
两种使用方法
-
接口
javapublic class main { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("线程启动"); } }; Thread thread = new Thread(runnable); thread.start(); } }
或者更常见的
javapublic class main { public static void main(String[] args) { Thread thread = new Thread( new Runnable() { @Override public void run() { System.out.println("线程启动"); } }); thread.start(); } }
-
类
任意的某个类
javaclass B { public void print() { System.out.println("B print"); } } public class main { public static void main(String[] args) { B b = new B(){ @Override public void print() { System.out.println("匿名继承父类"); } }; b.print(); } }
相当于 匿名内部类继承了B