java匿名内部类,多态,接口练习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java匿名内部类,多态,接口练习相关的知识,希望对你有一定的参考价值。
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; } }
以上是关于java匿名内部类,多态,接口练习的主要内容,如果未能解决你的问题,请参考以下文章
阶段1 语言基础+高级_1-3-Java语言高级_02-继承与多态_第7节 内部类_14_匿名内部类的注意事项
从零开始的Java开发1-4-4 多态与内部类:接口:定义并测试抽象方法常量默认方法静态方法重名默认方法和重名静态方法的解决方案继承;成员静态方法匿名 内部类