How it is restricted that subclass of java.lang.Throwable will not be generic class?
This was a decision to write a special case into the compiler itself. The reason why is detailed in this question. Basically, this is to do with a type being reifiable. You can read about this term here. In short, a type is reifiable if it's type is fully available at compile time. Generic types, for example, are not reifiable, because their types are removed by type erasure. Objects appearing in a catch
block need to be reifiable.
Or more generic question, how to restrict that subclasses of a class cannot be generic?
Well there's a few options..
At present, there is no option within the normal bounds of Java to do this. It doesn't have some sort of final
implementation that prevents genericity being applied to subclasses. The closest thing you can get to this, as explained in the comments, is to extend the compiler and add a rule specifically for your class. This solution sends shivers down my spine. Dodge it. It means that your code will only behave with your version of Java, and that anyone else who wants to use your code will have to install the same version.
Obviously, the other option is to extend Throwable
, but this really isn't a good idea. It adds a whole bunch of functionality to your class, and adds a lot of new methods to the interface of your class, that you will never use. From an OOP point of view, you're sacrificing the integrity of your class for the benefit of having this feature.