Skip to content
Advertisement

Java Problem: Calculations in one subclass’ constructor affecting fields of another subclass’ instance

I have two abstract classes i.e. Medicine and Prescription. All code can be found at https://codeshare.io/aVAdr3 These two classes have subclasses, the class hierarchy diagram is as follows:

enter image description here

and…

enter image description here

The medicine java file:

JavaScript

The Prescription java file:

JavaScript

The test program is as follows:

JavaScript

And when you run the test program you get this in the terminal:

JavaScript

I’ve been trying to solve this for hours, I can’t figure out how I can perform calculations in the pPrescription constructor without affecting instances of bluePrescription. Why is this happening? pPrescription is a subclass of whitePrescriptions, not bluePrescriptions. Anyhow, to instances of a class are completely separate, getPrice and setPrice are not static, so why is using them affecting all the instances of Medicine?

Advertisement

Answer

why is using them affecting all the instances of Medicine?

There is only once instance of Medicine in your code.

You pass the same object, i.e. drug1 to both pPrescription and bluePrescription class constructors.

As there’s only one object (drug1) that is passed to both classes, if any class modifies it, changes will be reflected everywhere you refer to that object.

One way to fix the problem is to not save the discounted price and just calculate it whenever you need it using a method in the pPrescription class.

JavaScript

Side note: Class names should begin with a capital letter.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement