#How to create constructor equivalent (is this bad practise)

19 messages · Page 1 of 1 (latest)

eternal lion
#

this is my original code (which works):


public class CargoHold extends Room {

    private int maximumCapacity;
    private List<ResourceContainer> resources;

    public CargoHold(RoomTier tier) {
        super(tier);
        this.maximumCapacity = maximumCapacityFinder(tier);
        this.resources = new ArrayList<ResourceContainer>();
    }
lime violetBOT
#

This post has been reserved for your question.

Hey @eternal lion! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

eternal lion
#

how do i do it properly

#

to get this

#

public class CargoHold extends Room {

    private int maximumCapacity;
    private ArrayList<ResourceContainer> resources;

    public CargoHold(RoomTier tier) {
        super(tier);
        this.maximumCapacity = maximumCapacityFinder(tier);
        this.resources = resources;
    }
#

when i do ^^^ the rest of my code breaks

tribal kite
eternal lion
#

oh

#

so how do i initialise it?

#

is my original code actually correct

tribal kite
#

yeah like you did in your original code

eternal lion
#

ohhh

#

and is that like, conventionally fine?

#

and wont cause problems with future code

#

i thought it would be wrong to have new inside the constructor

tribal kite
#

The entire purpose of the constructor is to make the object functional. It shouldn't have any side effects, meaning it shouldn't change the state of another object but it should do everything needed to put the object in a sort of default state when the object can be used.

native anchor
#

You can just do new ArrayList<>(); btw. The type is already specified in the variable declaration.

#

If you never want to change the list object, you can also do:

 private int maximumCapacity;
 private final ArrayList<ResourceContainer> resources = new ArrayList<>();