Why is java.net.URL final?

I would like to inherit from java.net.URL , but I can not, because it is final. I get an error message:

cannot inherit from final java.net.URL 

Why is this final?

Some answers to questions about why String is final indicate that the JVM relies on String because it is a very simple data type. I don’t see how this applies to the type of URL.

Update

Many answers and comments provide reasons why it is good practice to avoid inheritance. Some even think that everything should be final. But reality is something else. Most classes in the JDK are not final. Being good practice is the reason why one should not inherit from java.net.URL. This can even apply to any JDK class. But when something is defined as final, it may not inherit. This only applies to some very few classes in the form of a String or URL.

So there must be something else between the URL and all the other fuzzy classes. The question is: what is the difference, what makes the URL final?

Stating that I should not care about this question because I should not inherit, this is not the answer to the question.

+7
source share
3 answers

This is final so that you do not expand it. However, it works internally , it is not intended for inheritance, so the authors will prevent you from doing this.

Remember effective Java:

  • Paragraph 17: “Design and document for inheritance or prohibition”.
  • Paragraph 16: “Use composition over inheritance.

So, instead of extending the URL , create a class with a URL field.

+6
source

I assume this is for security reasons. If a method needs a URL object as a parameter, and you can extend the URL class to do something that should not execute the URL class, this can lead to a security problem.

+2
source

AFAIK URL is a complete implementation of IETF RFC standards, so you are not expected to want to change or expand it.

0
source

All Articles