Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to affect all objects of a class? (Java)

I was a bit unsure about how to formulate this question. It is about object oriented thinking, in my case in Java, but it's more about the general concepts.

To practice arrays and inheritance and such I want to create a little system where there are Car objects that can be owned by People objects, who store their cars in arrays. The cars will have a value, and the People objects can buy and sell cars from each other with money.

MY QUESTION:

I want there there to be a subroutine I can call to let a year pass, which will increase a year counter, and decrease the price of all cars currently existing in the program, as well as increase their "age" by 1. Things like that.

I realize I have no idea how to do something like this; how do I perform such an action, that targets not a specific object, but every object of a specific class? I imagine this type of operation is very common in big programs, how do you usually go about it?

like image 697
zxz Avatar asked Jun 24 '26 13:06

zxz


2 Answers

You cannot, really. At least not cleanly.

First off, you need to hold a reference to your Car objects, or they will be garbage collected (deleted from memory).

Since you're keeping a reference to them (probably under People objects), you could either go through all your people and get their cars, or you could keep a separate container (say, an ArrayList) that keeps all the Cars. That'd mean the cars are available either through people, or your separate container. Then you itereate through the container and do as you wish on the cars.

like image 104
Miquel Avatar answered Jun 26 '26 04:06

Miquel


To be able to age the car by one year, you just need a property int buildYear inside Car class.

The second part of the question. Each Car gets a property float amortizationPercentPerYear. Based on the age of a car, amortiationPercentPerYear and initial price you can calculate the exact price.

like image 21
WeMakeSoftware Avatar answered Jun 26 '26 03:06

WeMakeSoftware



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!