inheritance – Sticky situation where accessing parent functions is necessary in Java – Education Career Blog

I’ve been working on an economy simulator in Java and ran into a roadblock. I have an Economy class that owns a vector of Traders. Every iteration, the Economy class calls each Trader to update() and decide what trades it would like to place. The update() function returns the desired transactions to be added to the queue in the parent Economy class. I was able to implement all of the above correctly, but I still need each Trader to be able to see how many trades he currently has open. Since the trades are stored in the parent Economy class, how should I design the code so that the Traders do have access to Economy functions and variables?

,

Since the Trader class needs access to the methods of the Economy class, the correct way is to “inject” an instance of an Economy to the Trader class. You can do that either with the constructor:

public Trader(Economy economy) {
    this.economy = economy;
}

or with a setter:

public void setEconomy(Economy economy) {
        this.economy = economy;
    }

Be careful however to design the Economy class properly. Access to the variables of the Economy class should be restricted to the class’s methods only. Define getters and setters if you want to access them externally. As I understand it, Traders should only extract information from an Economy. They shouldn’t be able to call methods that modify the state of the Economy. This should be reflected on your design.

You may also consider defining an interface:

interface IEconomy {
  List<Trade> getTrades(Trader trader);
}

and implement it by the Economy class. Then inject an IEconomy to the Trader. This makes quite evident what parts of the Economy a Trader should use.

,

public class Trader {
    private Economy parent;
    ...
    public Trader(Economy parent, ...) {
        this.parent = parent;
    }
}

Now Trader should have access to the parent Economy.

Or:

public onUpdate(Economy parent) { ... }

if you wish.

,

The method update in the Trader class may take one argument, namely a reference to the Economy class, which you can pass using this. Then, Economy may provide the methods required to extract the desired information.

Leave a Comment