家用电器的多态性(1)

(一)派生类方式
定义抽象的家用电器类,并在此基础上定义具体的家电类,如电视机类、空调类、微波炉类,定义父类对象并使其在不同时刻表示子类对象,并使子类对象表示出自身的工作状态。
具体的:定义家用电器抽象类equipment,有功率power私有浮点域,有计算电量公有方法,参数为时间,用电量等于功率乘时间。然后定义电视机tv类、空调air-conditioner类、微波炉microwave-oven类,都继承自家用电器类。不同类型或相同类型的设备品牌不同,功率可能都不同;
要求main方法中至少包含如下形式代码(这些语句不要求必须放在一起):
equipment e;
e=new tv(power);
e=new air-conditioner(power);
e=new microwave-oven(power);
e.computequantity(time);
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.*;

abstract class equipment {
	public double power;

	public abstract void computequantity(double time);

	public void sc(String S) {
	}
}

class tv extends equipment {

	public tv(double power) {
		this.power = power;

	}

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

	public void computequantity(double time) {
		// TODO Auto-generated method stub

		double t = time * power;

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

}

class air extends equipment {
	public air(double power) {
		this.power = power;
	}

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

	@Override

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

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

}

class microwave extends equipment {
	public microwave(double power) {
		this.power = power;
	}

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

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

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

}

public class Main {

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		double power, time = 0;
		char s;
		int q=1;
		double t = 0;
		String S = null;
		equipment e = null;
		while (q>0) {
			s = in.next().charAt(0);

			S = in.next();

			if (s == 'T') {

				power = in.nextDouble();
				time = in.nextDouble();
				e = new tv(power);
				e.sc(S);
				e.computequantity(time);
			}
			if (s == 'A') {

				power = in.nextDouble();
				time = in.nextDouble();
				e = new air(power);
				e.sc(S);
				e.computequantity(time);
			}
			if (s == 'M') {
				power = in.nextDouble();
				time = in.nextDouble();
				e = new microwave(power);
				e.sc(S);
		e.computequantity(time);
			}
		}

	}

}

你可能感兴趣的:(Java)