Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is java.net.URL final?

Tags:

java

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.

like image 903
ceving Avatar asked Sep 12 '12 15:09

ceving


1 Answers

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:

  • Item 17: "Design and document for inheritance or else prohibit it."
  • Item 16: "Favor composition over inheritance."

So instead of extending URL, create a class which has a URL field.

like image 134
Matt Ball Avatar answered Oct 25 '22 16:10

Matt Ball