javaobjectconstructorcreationdestruction

We initialize our main object, and it creates a new object in its constructor. When we destroy the main object, what happens to its creation?


I think the title is very specific, but here's some code to exemplify the question. Also, I realize that aggregation would be the right choice for this particular example, and maybe the question itself poses an OOP smell; however, while I am interested in OOP, I'm more interested in how Java handles object destruction here.

public class SuperMarket
{

    private Cashier mCashier;

    public SuperMarket(...)
    {

        this.mCashier = new Cashier(...);

    }

}

And running.

listSuperMarkets.add(new SuperMarket(...));

What happens here, where no other references exist (that may not matter, not sure when writing this):

listSuperMarkets.remove(0);

Solution

  • As @tkausl mention the garbage collector will delete the object, but to be more specific your object will exist in the heap until the garbage collector delete it.