-->
当前位置:首页 > 题库 > 正文内容

主观题:设计一个设备类及其子类计算机类

Luz3年前 (2022-05-24)题库523
现有如下的测试程序:

public class TestEquipment {
public static void main(String[] args) {
Equipment e = new Equipment(8000,"联想");
System.out.println(e);
Computer c = new Computer(12000,"戴尔",16);
System.out.println(c);
}
}

输出结果如下:

联想的价格为:8000.0

戴尔的价格为:9600.0
内存为:16G


根据以上测试结果,采用Java语言,按照如下要求编写程序:

1、定义Equipment类,表示电子设备。其中:

(1)有两个私有成员:一个double类型的price变量表示价格,一个String类型的name表示设备名称。

(2)定义一个无参构造方法.

(3)定义一个带有price和name两个参数的构造方法。

(4)分别定义price和name的get/set方法。

(5) 定义一个toString()方法,输出信息描述。

2、定义一个Computer类继承Equipment类,表示计算机。其中:

(1)一个int类型的私有成员ram,表示单位为G的内存容量。

(2)定义一个带有price和name两个参数的构造方法。

(3)定义一个带有price、name和ram参数的构造方法。

(4)重写getPrice()方法,当价格高于10000元时打8折,否则为原价。

(5)重写toString()方法,其中调用父类的toString()方法,输出信息描述。






答案:
1、定义Equipment类,基本结构正确(1分)

(1)有两个私有成员:一个double类型的price变量表示价格,一个String类型的name表示设备名称。(2分)

(2)定义一个无参构造方法.(1分)

(3)定义一个带有price和name两个参数的构造方法。(2分)

(4)分别定义price和name的get/set方法。(2分)

(5) 定义一个toString()方法,输出信息描述。(2分)

2、定义一个Computer类继承Equipment类,表示计算机。继承结构正确(1分)

(1)一个int类型的私有成员ram,表示单位为G的内存容量。(1分)

(2)定义一个带有price和name两个参数的构造方法。(2分)

(3)定义一个带有price、name和ram参数的构造方法。(2分)

(4)重写getPrice()方法,当价格高于10000元时打8折,否则为原价。(2分)

(5)重写toString()方法,其中调用父类的toString()方法,输出信息描述。(2分)


参考程序:

class Equipment {
private double price;
private String name;

public Equipment() {
}

public Equipment(double price, String name) {
this.price = price;
this.name = name;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return name + "的价格为:" + getPrice()+"\n";
}
}
class Computer extends Equipment {
private int ram;

public Computer(double price, String name) {
super(price, name);
}

public Computer(double price, String name, int ram) {
super(price, name);
this.ram = ram;
}

public int getRam() {
return ram;
}

public void setRam(int ram) {
this.ram = ram;
}
@Override
public double getPrice() {
if (super.getPrice()>10000)
return 0.8*super.getPrice();
else
return super.getPrice();
}

@Override
public String toString() {
return super.toString() + "内存为:"+ram +"G";
}
}

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。