interface USB { void start(); void end(); } @Test public void testInterface() { USB u = new USB() { public void start() { System.out.println("匿名类start"); } public void end() { System.out.println("匿名类end"); } }; u.start(); u.end(); }
第二种方法
class Computer { void doWork(USB u) { u.start(); u.end(); } } interface USB { void start(); void end(); } public void testComputer() { Computer com = new Computer(); com.doWork(new USB() { public void start() { System.out.println("start work"); } public void end() { System.out.println("start end"); } }); }