java - Java 问题:一个子类的构造函数中的计算会影响另一个子类实例的字段
问题描述
我有两个抽象类,即医学和处方。所有代码都可以在https://codeshare.io/aVAdr3找到这两个类都有子类,类层次图如下:
和...
医药java文件:
abstract class Medicine {
public String name;
public int price;
public Medicine (String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice () {
return price;
}
public void setPrice (int newPrice){
price = newPrice;
}
}
class commonDrug extends Medicine {
public commonDrug (String name, int price) {
super(name, price);
}
}
处方 java 文件:
abstract class Prescription {
protected Medicine med;
public Prescription(Medicine med) {
this.med = med;
}
}
class bluePrescription extends Prescription {
public bluePrescription (Medicine med) {
super(med);
System.out.println(med.getPrice()+ "<-- Price for bluePrescription, it should be 30, but the calculations in pPrescriptions affect it.");
}
}
class whitePrescription extends Prescription {
public whitePrescription (Medicine med) {
super(med);
}
}
class pPrescription extends whitePrescription {
public pPrescription (Medicine med) {
super(med);
System.out.println(med.getPrice()+ "<-- Price before calculation for pPrescription");
//Calculations
int priceWithDiscount;
if (med.getPrice()<=20) {priceWithDiscount=0;}
else {priceWithDiscount= med.getPrice()-20;}
med.setPrice(priceWithDiscount);
System.out.println(med.getPrice()+ "<-- Price after calculation for pPrescription");
}
}
测试程序如下:
class TestProgram {
public static void main (String[] args) {
//Medicine object
commonDrug drug1 = new commonDrug("Paracetamol", 30);
//Prescription objects:
pPrescription prescription1 = new pPrescription(drug1);
bluePrescription prescription2 = new bluePrescription(drug1);
}
}
当你运行测试程序时,你会在终端中得到这个:
30<-- Price before calculation for pPrescription
10<-- Price after calculation for pPrescription
10<-- Price for bluePrescription, it should be 30, but the calculations in pPrescriptions affect it.
我已经尝试解决这个问题好几个小时了,我无法弄清楚如何在 pPrescription 构造函数中执行计算而不影响 bluePrescription 的实例。为什么会这样?pPrescription 是 whitePrescriptions 的子类,而不是 bluePrescriptions。无论如何,对于一个类的实例是完全独立的,getPrice 和 setPrice 不是静态的,那么为什么使用它们会影响 Medicine 的所有实例呢?
解决方案
为什么使用它们会影响医学的所有实例?
Medicine
您的代码中只有一个实例。
您将相同的对象传递drug1
给两个pPrescription
和bluePrescription
类构造函数。
由于只有一个对象drug1
(
解决此问题的一种方法是不保存折扣价,只需在需要时使用pPrescription
类中的方法进行计算。
class pPrescription extends whitePrescription {
...
public int getDiscountedPrice() {
return med.getPrice() <= 20 ? 0 : med.getPrice() - 20;
}
}
旁注:类名应以大写字母开头。
推荐阅读
- python - 使用网络摄像头 OpenCV 将多条线连接到屏幕中心
- selenium - 使用 Data Provider 的 TestNG 并行测试
- ruby - 如何通过 Ruby 控制器使用 Multipart/form-data?
- r - 如何创建带有特殊字符的字符串
- swift - 在 WebView 中触发按钮
- c - 用于返回结构的 C 宏
- python - 为什么 datetime.datetime.fromtimestamp 引发 OSError: [Errno 22] Invalid argument
- xaml - 将 Xamarin 表单选项卡式页面连接到 XAML
- ember.js - Ember:运行循环:如何知道作业是否已安排或完成
- pagination - @Html.PagedListPager 不在查询字符串中发送页面