fernando1979
fernando1979

Reputation: 1947

Inner class as a part of an outer class

Let's suppose that I have a shop of toys. And I have a web page where these toys can be bought. Each toy has its own features but to represent a human toy I have a class called HumanToy with some properties like height, weight.... But I have a nested property that it itself a JavaBean called HumanLegs and this class has its own features like:

public class HumanToy {     

    private Double height;
    private Double weight;

    private HumanLegs humanLegs;

    private class HumanLegs {

        private Double height;
        private Double weight;
    }

My question would be:

Does it make any sense that this toy has a static HumanLegs class? I mean, conceptually, HumanLegs cannot exist by its own, they only exist with a toy so I think its logical that this is an inner class at first (not a separated class), and secondly not static for the same reason, I mean, only instantiating a HumanToy you can get a HumanLegs object or to get a HumanLegs object you need a HumanToy object. Is this the right thinking?

Upvotes: 3

Views: 82

Answers (1)

wiomoc
wiomoc

Reputation: 1089

Yes it makes sense because HumanLegs keeps a reference to his outer class. If you move the instance of HumanLegs to an other instance of HumanToy the originating HumanToy will not be deleted because HumanLegs does keep a reference to it.

The outerclass is thus kept in memory for at least as long as all instances of the innerclass.

Upvotes: 3

Related Questions