我知道如何通过创建一组从具有私有构造函数的类继承的最终内部类来实现寡态,但这似乎有点不合适。
I wouldn't say this technique is inappropriate - the real problem is that mainstream OOP languages lack a mechanism to define a type by cases. Doing this conflates cases with types (unless you hide the subclasses by making them private) but it's the only option you have in Java.
ruakh's answer addresses your question about the sealing mechanism so I'll skip that. As for avoiding the Fragile Base Class Problem,
this paper presents a solution that currently works in Java. The idea is to make all public methods
final
and implement them in terms of
protected
methods. This ensures that subclasses can only override those methods you deem safe.
The problem with inheritance as implemented in mainstream OOP languages is that it's something you have to opt out of when it should be something you have to opt into. That said, other than defining a type by cases I'm not sure what other use inheritance has that's not better replaced with aggregation/composition.