When is really useful to use a nested Java class?

后端 未结 4 984
猫巷女王i
猫巷女王i 2021-01-25 03:52

Could you give me a concrete example where a nested java class is useful? I am studying it, I understand how it works but I can not imagine a real situation where its use is rea

4条回答
  •  无人及你
    2021-01-25 04:27

    I found them useful when I have classes that are part of one another evolving together. For instance, if I have base abstract classes:

    abstract class Unit {
      private int HP;
      ....
      abstract class AI {
        abstract void heal();
      }
    }
    

    Later on, I can specify which type of unit I'm designing:

    class Infantry extends Unit {
      ...
      class InfantryAI extends AI {
        void heal() { this->HP++; }
      }
    }
    

    What you see there is a secondary this - non-static nested classes (aka inner classes like AI and InfantryAI) can access their surrounding classes' (Unit and Infantry) private attributes as their own, and that access right propagates down the inheritance tree.

    As for them being necessary - none of these OOP constructs are really necessary, but if it makes sense to you during design phase (like I thought it might be logical that AI is part of every Unit type so that it can control even it's private members), then you can use them.

提交回复
热议问题