Reputation: 23871
I would like to inherit from java.net.URL but I can not because it is final. I get the error:
cannot inherit from final java.net.URL
Why is it final?
Some answers for the questions why String is final state, that the JVM relies on String because it is a very basic data type. I can not see how this would apply to the URL type.
Update
Many answers and comments are giving reasons, why it is good practice to avoid inheritance. Some even think that everything should be final. But the reality is something different. Most classes in the JDK are not final. Being good practice is a reason why one should not inherit from java.net.URL. This might even apply to any class of the JDK. But when something is defined as final one can not inherit. This applies only to some very few classes as String or URL.
So there must be something different between URL and all the other non final classes. The question is: what is this difference, that makes it necessary, that URL is final?
Stating that I should not care about this question, because I should not inherit anyway is no answer to the question.
Upvotes: 7
Views: 1121
Reputation: 360016
It's final specifically to prevent you from extending it. However it works internally, it was not designed for inheritance, so the authors prevent you from doing so.
Remember Effective Java:
So instead of extending URL
, create a class which has a URL
field.
Upvotes: 7
Reputation: 533870
AFAIK the URL is the full implementation of the IETF RFC standards so it is not expected you would want to change or extend it.
Upvotes: 0
Reputation: 8969
My guess is that this is for security reason. If a method required URL object as a parameter and you could extend the URL class to do something that the URL class shouldn't do then it could have a security problem.
Upvotes: 2