Java接口练习

文章目录

题目

定义一个接口,其中包含一个 display ( )方法用于显示信息:通知类、汽车类、广告类均要实现该接口,以显示“通知内容”、“汽车油量”、“广告消息”。试编程实现并测试类的设计。创建的对象用接口引用,并通过接口引用变量执行 display ( )方法。

代码

public class Port {
    public static void main(String[] args) {
        Input data[] = new Input[3];
        data[0] = new Notice(“Hello”);
        data[1] = new Car(15);
        data[2] = new Ad(“Hi”);
        for(int i = 0; i < data.length; i++)
            show(data[i]);
    }
  public static void show(Input a) {
        if(a instanceof Notice)
            System.out.println(“通知内容为:”);
        else if(a instanceof Car)
            System.out.println(“汽车油量为:”);
        else if(a instanceof Ad)
            System.out.println(“广告内容为:”);

System.out.println(a.display());
    }
}

interface Input {
    abstract String display();
}

class Notice implements Input {
    String str;
    public Notice(String str) {
        this.str = str;
    }
    public String display() {
        return str;
    }
}

class Car implements Input {
    float num;
    public Car(float num) {
        this.num = num;
    }
    public String display() {
     return num + “”;
    }
}

class Ad implements Input {
    String str;
    public Ad(String str) {
        this.str = str;
    }
    public String display() {
       return str;
    }
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值