JavaSE-12.2.4【匿名内部类在开发中的使用】
package day3.yub4by02.p4; /* 2.5 匿名内部类在开发中的使用 当发现某个方法需要,接口或抽象类的子类对象, 就可以传递一个匿名内部类过去,来简化传统代码 */ public class JumppingDemo { public static void main(String[] args) { JumppingOperator jo = new JumppingOperator(); // Jumpping j = new Cat(); // jo.method(j); // // Jumpping j2 = new Dog(); // jo.method(j2); //省去单独编写Cat Dog类 jo.method( new Jumpping() { @Override public void jump() { System.out.println("兔子跳多高"); } } ); jo.method( new Jumpping() { @Override public void jump() { System.out.println("猪猪跳多高"); } } ); } }
package day3.yub4by02.p4; public class JumppingOperator { public void method(Jumpping j){ //new Cat();new Dog();new xxx(); ..... j.jump(); } }
package day3.yub4by02.p4; public interface Jumpping { void jump(); }
package day3.yub4by02.p4; public class Cat implements Jumpping{ @Override public void jump() { System.out.println("猫猫跳多高"); } }
package day3.yub4by02.p4; public class Dog implements Jumpping{ @Override public void jump() { System.out.println("狗狗跳多高"); } }