Are sealed classes enforced in Java and, if yes, how?
It is possible to define sealed
开发者_开发问答classes in Scala, which are basically final
except if the sub-classing happens in the same file.
It seems that the JVM doesn't allow final
class bytecode and subclasses of it.
Considering that there is no "notion" of source file in the bytecode, how is this restriction enforced?
Therefore, how can javac
prevent a Scala sealed
class from being sub-classed in Java?
The restriction is enforced for Scala source by scalac at compile time. The resulting binary class definitions don't have the JVMs final flag set so, as you've probably guessed by now, the sealed restriction will not be enforced by javac when Java sources are compiled against Scala binaries.
How about using a private constructor for the class you would like to seal, and then create public final static inner classes that extends that class. Then you get a fixed set of subclasses at compile time that can't be extended further. The base class with the private constructor subsequently serves as a path to reach those inner classes, but is in itself impossible to extend and implement elsewhere.
精彩评论