【训练2】水果售价
使用继承,展示经过人工包装的水果与普通水果在价格上的区别。
主类调用水果类和精装水果类
/*【训练2】水果售价
* 使用继承,展示经过人工包装的水果与普通水果在价格上的区别。
*
* */
package JcDtCxlhJk;
public class Xl2 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
//设置水果名称价格重量
Fruit fruit = new Fruit();//调用水果类,创建对象
fruit.setName("苹果");//设置水果名称,初始化水果名称
fruit.setPrice(1.98);//设置水果价格,初始水果价格
fruit.setWeight(5);//设置水果重量,初始化水果重量
//设置精装水果名称价格重量
PackageFruit packagefruit = new PackageFruit();
packagefruit.setName("精装水果");
packagefruit.setPrice(2.98);
packagefruit.setWeight(5);
packagefruit.setPackagefee(packagefruit.getPrice()-fruit.getPrice());//包装费
//输出水果信息
System.out.println("水果名称\t水果价格(元/千克)\t水果重量(千克)\t包装费(元/千克)\t总价"); // 提示信息
System.out.println("————————————————————————————————————————————————————————————");
System.out.println(fruit.getName()+"\t"+fruit.getPrice()+"\t\t"+fruit.getWeight()+"\t\t"+
+0.0+"\t\t"+fruit.getPrice()*fruit.getWeight());
System.out.println(packagefruit.getName()+"\t"+packagefruit.getPrice()+"\t\t"+packagefruit.getWeight()+"\t\t"+
+packagefruit.getPackagefee()+"\t\t"+packagefruit.getPrice()*packagefruit.getWeight());
//输出两种水果总价的差价
System.out.println("————————————————————————————————————————————————————————————");
System.out.println("差价\t\t\t\t\t\t\t"+ (packagefruit.getPrice()*packagefruit.getWeight() - fruit.getPrice()*fruit.getWeight()) );
}
}
水果类
/*水果类:定义水果名称、水果重量、水果价格
*
* */
package JcDtCxlhJk;
public class Fruit {
// 定义成员变量
private String name; // 水果名称
private double weight; // 水果重量
private double price; // 水果价格
//定义构造方法
//名称
public String getName(){ // 获得水果名称:返回成员变量
return name;
}
public void setName(String name) { // 设置水果名称:给成员变量赋值参数
this.name = name;
}
//重量
public double getWeight(){ // 获得水果重量:返回成员变量
return weight;
}
public void setWeight(double weight) { // 设置水果重量:给成员变量赋值参数
this.weight = weight;
}
//价格
public double getPrice(){ // 获得水果价格:返回成员变量
return price;
}
public void setPrice(double price) { // 设置水果价格:给成员变量赋值参数
this.price = price;
}
}
精装水果类
/* 包装过的水果,继承水果类,特有属性:包装费 */
package JcDtCxlhJk;
public class PackageFruit extends Fruit {
private double packagefee;//定义“包装费”
public double getPackagefee() { // 获得“包装费”
return packagefee;
}
public void setPackagefee(double packagefee) { // 设置“包装费”
this.packagefee = packagefee;
}
}
输出结果