家用电器的多态性(2)

(二)接口方式
定义用电量接口,然后定义实现该接口的电视机类、空调类、微波炉类。统一用接口变量指向实现该接口类对象,从而实现多态。
具体的:定义用电量接口Icomputequantity,有computequantity()方法。然后定义电视机tv类、空调air-conditioner类、微波炉microwave-oven类,都实现此接口,另外它们都有品牌名、功率、时间等私有域。不同类型或相同类型的设备如果品牌不同,功率可能都不同;
要求main方法中至少包含如下形式代码(这些语句不要求必须放在一起):
Icomputequantity ic;
ic=new tv(……);
ic=new air-conditioner(……);
ic=new microwave-oven(……);
ic.computequantity();
注:……表示参数列表
Input
有N组数据。每组数据由一个字符、一个字符串和一个整型数组成,第一个如何是’T’表示电视;是’A’表示空调;是’M’表示微波炉。而后是设备品牌字符串,然后是功率和时间,都是浮点数。
Output
每种设备的耗电量。保留两位小数,参见样例。
Sample Input
T sony 100 20
A aier 200 20
M simens 80 20

Sample Output
sony:2000.00
aier:4000.00
simens:1600.00

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		double power, time;
		char s;
		while (in.hasNext()) {
			s = in.next().charAt(0);
			Icomputequantity ic;
			if (s == 'T') {
				String S = in.next();
				power = in.nextDouble();
				time = in.nextDouble();
				ic = new tv();
				ic.sc(S);
				ic.computequantity(power, time);
			}
			if (s == 'A') {
				String S = in.next();
				power = in.nextDouble();
				time = in.nextDouble();
				ic = new air();
				ic.sc(S);
				ic.computequantity(power, time);
			}
			if (s == 'M') {

				String S = in.next();
				power = in.nextDouble();
				time = in.nextDouble();
				ic = new mic();
				ic.sc(S);
				ic.computequantity(power, time);

			}
		}
	}

}

interface Icomputequantity {

	void computequantity(double power, double time);

	void sc(String S);
}

class tv implements Icomputequantity {
	double power;
	double time;

	@Override
	public void sc(String S) {
		// TODO Auto-generated method stub
		System.out.print(S + ":");
	}

	@Override
	public void computequantity(double power, double time) {
		// TODO Auto-generated method stub

		double t = time * power;

		System.out.printf("%.2f\n", t);
	}

}

class air implements Icomputequantity {
	double power;
	double time;

	@Override
	public void sc(String S) {
		// TODO Auto-generated method stub
		System.out.print(S + ":");
	}

	@Override
	public void computequantity(double power, double time) {
		// TODO Auto-generated method stub
		double t = time * power;

		System.out.printf("%.2f\n", t);
	}

}

class mic implements Icomputequantity {
	double power;
	double time;

	@Override
	public void sc(String S) {
		// TODO Auto-generated method stub
		System.out.print(S + ":");
	}

	@Override
	public void computequantity(double power, double time) {
		// TODO Auto-generated method stub
		double t = time * power;

		System.out.printf("%.2f\n", t);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不关我事~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值