1多态以及接口调用方法:
public class Interface { public static void main(String[] args) { Al x = new Al(); jian a = x; System.out.println(a.sub(1, 2)); // 使用接口引用调用的方法 animal zz = new animal(); zz.jiao(); zz = new dog(); zz.jiao(); zz = new cat(); zz.jiao(); //多态 } } interface jia{ public int add(int x, int y); } interface jian{ public int sub(int x, int y); } interface cheng{ public int mul(int x, int y); } interface chu{ public int del(int x, int y); } class Al implements jia,jian,cheng,chu{ public int sub(int x, int y){ return x - y; } public int add(int x, int y){ return x + y; } public int mul(int x, int y){ return x * y; } public int del(int x, int y){ return x / y; } } class animal{ public void jiao(){ System.out.println("我是animal"); } } class dog extends animal{ public void jiao(){ System.out.println("汪汪"); } } class cat extends animal{ public void jiao(){ System.out.println("喵喵"); } }
2.匿名内部类练习:
public class 匿名内部类 { public void drink(Beverages drink){ System.out.println("运动员在饮用" + drink); } public static void main(String[] args) { DustMan dm = new DustMan(); dm.cleanWithBroom(); dm.cleanWithDustCollector(); 匿名内部类 sp = new 匿名内部类(); sp.drink(new Beverages("橙汁"){ public void addsomething(){ System.out.println("橙汁老司机开车了"); } }); sp.drink(new Beverages("可乐"){ public void addsomething(){ System.out.println("可乐老司机开车了"); } }); sp.drink(new Beverages("雪碧"){ public void addsomething(){ System.out.println("雪碧老司机开车了"); } }); sp.drink(new Beverages("芬达"){ public void addsomething(){ System.out.println("芬达老司机开车了"); } }); sp.drink(new Beverages("绿茶"){ public void addsomething(){ System.out.println("绿茶妹妹开车了"); } }); } } class DustMan{ public void cleanWithBroom(){ Utility util = new Utility(){ public void clean(){ System.out.println("正在清洁卫生。。。"); } }; util.clean();//调用前面的方法; } public void cleanWithDustCollector(){ ElectronicUtil util = new ElectronicUtil(){ public void clean(){ System.out.println("正在用吸尘器清洁卫生。。。"); } }; util.clean();//调用前面的方法; } } interface Utility{ public void clean(); } class ElectronicUtil{ public void clean(){ System.out.println("使用电子设备清洁卫生...."); } } class Beverages{ private String juiceName; public Beverages(String name){ this.juiceName = name; } public String toString(){ return juiceName; } }
时间: 2024-10-25 06:06:33