JAVA 匿名内部类
public interface A { public void func(); }
public class B implements A { public B() { // TODO Auto-generated constructor stub } @Override public void func() { // TODO Auto-generated method stub System.out.println("func B"); } }
public class C implements A { A a; public C() { // TODO Auto-generated constructor stub } public C(A a) { // TODO Auto-generated constructor stub this.a = a; } @Override public void func() { // TODO Auto-generated method stub System.out.println("func C"); a.func(); } }
两种实现方式
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub B b = new B(); C c = new C(b); c.func(); C c1 = new C(new A() { @Override public void func() { // TODO Auto-generated method stub System.out.println("new A()"); } }); c1.func(); } }
运行结果
func C func B func C new A()