简体   繁体   English

为什么java.net.URL最终?

[英]Why is java.net.URL final?

I would like to inherit from java.net.URL but I can not because it is final. 我想继承java.net.URL,但我不能,因为它是最终的。 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. 对于为什么String是最终状态的问题的一些答案,JVM依赖于String,因为它是一种非常基本的数据类型。 I can not see how this would apply to the URL type. 我看不出这将如何适用于URL类型。

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. JDK中的大多数类都不是最终的。 Being good practice is a reason why one should not inherit from java.net.URL. 良好的做法是一个不应该继承java.net.URL的原因。 This might even apply to any class of the JDK. 这甚至可能适用于JDK的任何类。 But when something is defined as final one can not inherit. 但是当某些东西被定义为最终的时候, 无法继承。 This applies only to some very few classes as String or URL. 这仅适用于极少数类,如String或URL。

So there must be something different between URL and all the other non final classes. 因此,URL和所有其他非最终类之间必定存在不同之处。 The question is: what is this difference, that makes it necessary, that URL is final? 问题是:这有什么不同,这是必要的,URL是最终的?

Stating that I should not care about this question, because I should not inherit anyway is no answer to the question. 说我不应该关心这个问题,因为我不应该继承这个问题是没有答案的。

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: 记住有效的Java:

  • Item 17: "Design and document for inheritance or else prohibit it." 第17项: “继承的设计和文件,否则禁止它。”
  • Item 16: "Favor composition over inheritance." 第16项: “赞成作品而不是继承。”

So instead of extending URL , create a class which has a URL field. 因此,不是扩展URL ,而是创建一个具有URL字段的类。

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. 如果方法需要URL对象作为参数,并且您可以扩展URL类以执行URL类不应该执行的操作,那么它可能存在安全问题。

AFAIK URL是IETF RFC标准的完整实现,因此不希望您想要更改或扩展它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM