140 - 家电类
Time Limit: 1000 Memory Limit: 65535
Submit: 396 Solved: 290
Description
某大型家电企业拥有一批送货卡车,运送电视机、洗衣机、空调等家电。编程计算每个卡车所装载货物的总重量。要求有一个Appliance(家电)接口和有三个实现类TV、WashMachine和AirConditioner,这些类能够提供自重。有一个Truck类,包含了该货车上的所有家电,用一个集合(数组或集合类)表示。
Main函数中程序能够输出Truck类所装载货物的总重量。
Input
家电数量
家电种类编号 家电重量
注意:各个家电的编号为:TV:1 WashMachine:2 AirConditioner:3
Output
总重量
Sample Input
5
1 20
2 30
3 25
3 30
2 40
Sample Output
145
接口的实现方式
public class Lion implements Predator {
public boolean chasePrey(Prey p) {
// programming to chase prey p (specifically for a lion)
}
public void eatPrey (Prey p) {
// programming to eat prey p (specifically for a lion)
}
}
public class Lion implements Predator {
public boolean chasePrey(Prey p) {
// programming to chase prey p (specifically for a lion)
}
public void eatPrey (Prey p) {
// programming to eat prey p (specifically for a lion)
}
}
如果一个类实现了一个接口,而没有实现接口的所有方法,则它必须被标注为abstract(抽象类)。一个抽象类的子类必须实现它未完成的方法,假如该项子类仍不会实现接口的所有方法,那么该项子类依然需要被标注为abstract。
接口通常被使用在Java编程语言,用来做回调函数使用[2] 。Java并不允许方法作为参数传递使用,因此,其中一个解决办法则是可以定义一个接口,把这个接口当成方法的参数,以此来使用该项对象的方法签名。
子接口[编辑]
接口可以被延伸为数个不同的接口,可以使用上述所描述的方法,举例来说:
public interface VenomousPredator extends Predator, Venomous {
//介面主體
}
以上的程序片段是合法定义的子接口,与类不同的是,接口允许多重继承,而Predator 及 Venomous 可能定义或是继承相同的方法,比如说kill(Prey prey),当一个类实现VenomousPredator的时候,它将同时实现这两种方法。
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Truck truck = new Truck();
truck.getScan();
System.out.println(truck.getSumWeight());
}
}
interface Appliance
{
public int getWeight();
}
class App implements Appliance
{
int weight;
public int getWeight()
{
return 0;
}
}
class TV extends App implements Appliance{
TV(int weight)
{
this.weight = weight;
}
@Override
public int getWeight()
{
return weight;
}
}
class WashMachine extends App implements Appliance{
WashMachine(int weight)
{
this.weight = weight;
}
@Override
public int getWeight()
{
return weight;
}
}
class AirConditioner extends App implements Appliance{
AirConditioner(int weight)
{
this.weight = weight;
}
@Override
public int getWeight()
{
return weight;
}
}
class Truck
{
int num;
App[] app;
int SumWeight;
public void getScan()
{
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
app = new App[num];
for(int i = 0; i<num; i++)
{
int type = scan.nextInt();
int w = scan.nextInt();
if(type == 1)
app[i] = new TV(w);
else if(type == 2)
app[i] = new WashMachine(w);
else if(type == 3)
app[i] = new AirConditioner(w);
}
}
public int getSumWeight()
{
for(int i = 0; i < num; i++)
{
SumWeight += app[i].getWeight();
}
return SumWeight;
}
}