So, I'm new in this field, still trying to learn. I'm trying to create a car with different options (start the engine, stop the engine, change the gear, reverse, neutral, fill it up, etc.) and now I'm trying to make 2 methods that will consume my fuel depending on the state of the car, if the engine is on it will consume 0.8 liters per minute, if it is moving to consume 6 liters per minute (I did put 6000 milliseconds to test the methods). The idea is that in the main class I already have a car type object created, how can I call its methods in the FuelConsumption class without creating a new object?
enter image description here(https://i.stack.imgur.com/YLUOX.png)
I know that I could make those methods static, or simply move everything to the Car class, but I don't think it's the most correct way to solve it, plus I'd like to find out the answer to this problem more for the purpose of learning.
CodePudding user response:
If you want to call Car's methods from the FuelConsumption class, the FuelConsumption class needs an instance of the Car class. But you can pass it in as parameter.
class FuelConsumption {
void consume(float amount, Car car) {
car.whatevermethod();
}
}
Passing that parameter should not be a problem from your main method so you do not have to create a separate instance:
public static void main(Strin[] args) {
Car car = new Car(...);
FuelConsumption fc = new FuelConsumption(...);
fc.consume(5.0f, car);
}