【训练2】水果售价

【训练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;
	}
}

输出结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值