博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java接口示例
阅读量:6669 次
发布时间:2019-06-25

本文共 2148 字,大约阅读时间需要 7 分钟。

接口示例

package auto.test;public class RerridingTest {    public static void main(String args[]){    test("Car","100","45","67" );    test("Plane","100","45","67" );    test("Bike","100","45","67" );        }    public static void test(String tool, String a,String b, String c) {        System.out.println("交通工具: " + tool);        System.out.println(" 参数A: " + a);        System.out.println(" 参数B: " + b);        System.out.println(" 参数C: " + c);        double A = Double.parseDouble(a);        double B = Double.parseDouble(b);        double C = Double.parseDouble(c);        double v, t;        try {            Common d = (Common) Class.forName("auto.test." + tool).newInstance();            v = d.runTimer(A, B, C);            t = 1000 / v;            System.out.println("平均速度: " + v + " km/h");            System.out.println("运行时间:" + t + " 小时");        } catch (Exception e) {            System.out.println("class not found");        }    }}class Plane implements Common {    public double runTimer(double a, double b, double c) {        return (a + b + c);    }}class Car implements Common {    public double runTimer(double a, double b, double c) {        return (a * b / c);    }}class Bike implements Common {    public double runTimer(double a, double b, double c) {        return ((a+b+c)*2);    }}interface Common {    double runTimer(double a, double b, double c);}

 

示例二

 

package auto.test;//1、先建一个动物接口,接口里面有吃的方法,没有方法体interface Animal {    public void eat();}//2 建一个狗的类,implements 动物类,Animalclass Dog implements Animal{    public void eat(){  //重写animal的eat 方法        System.out.println("eat bone");    }}//3 建一个猫的类,implements 动物类,Animalclass Cat implements Animal{    public void eat(){
//重写animal的eat 方法 System.out.println("eat fish"); }}//统一处理所有animal 类的行为class TestInterface{ public void getEat(Animal a){
// 传入动物类 a.eat(); }}//测试类class TestAnimal{ public static void main(String arg[]){ Dog d = new Dog(); Cat c = new Cat(); TestInterface te = new TestInterface(); te.getEat(d); te.getEat(c); } }

 

 

来源:http://blog.sina.com.cn/s/blog_48c0812c0101alaz.html

转载地址:http://jmoxo.baihongyu.com/

你可能感兴趣的文章