3

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?

2
  • 2
    Sure, if they cannot be separated in your conceptualized world, then this is exactly the right thinking. Remark: don't use the object wrappers for double if you don't have to. The HumanLegs member field should be written humanLegs. Nowadays a lot of people prefer immutable objects and builders over mutable beans, by the way. Oh, and you could just call it Legs I suppose, and reference it as HumanToy.Legs. Jan 8, 2019 at 23:29
  • Yup. Makes perfect sense. If you want to share code between HumanToyLeg and RobotToyLeg then, of course, they are free to implement / extend the ToyLeg interface / class
    – CJDood
    Jan 8, 2019 at 23:59

1 Answer 1

3

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.

1
  • The outer class is not allowed to leg it :) Jan 8, 2019 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.