首页 > 解决方案 > 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 的所有实例呢?

标签: javaobjectconstructorinstancesubclass

解决方案


为什么使用它们会影响医学的所有实例?

Medicine您的代码中只有一个实例。

您将相同的对象传递drug1给两个pPrescriptionbluePrescription类构造函数。

由于只有一个对象drug1

解决此问题的一种方法是不保存折扣价,只需在需要时使用pPrescription类中的方法进行计算。

class pPrescription extends whitePrescription {

    ...

    public int getDiscountedPrice() {
        return med.getPrice() <= 20 ? 0 : med.getPrice() - 20;
    }    
}

旁注:类名应以大写字母开头。


推荐阅读