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
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.