Java继承,扩展类如何影响实际的类 [英] Java Inheritance, how does a extending a class effect the actual class

查看:72
本文介绍了Java继承,扩展类如何影响实际的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在审查《 Sun认证》学习指南,其中有一段描述了最终修饰符.它说

I am reviewing the Sun Certification study guide and there is a passage which describes the final modifier. It says

如果程序员能够自由扩展String类文明,因为我们知道它可能会崩溃"

"If programmers were free to extend the String class civilisation as we know it could collapse"

他是什么意思? 如果可以扩展String Class ...,我是否将没有一个名为MyString的类,该类继承了所有Strings属性. 仅通过扩展它,怎么可能以任何方式更改实际的String类?

What does he mean ? If it were possible to extend String Class ... would I just not have a class called MyString which inherits all of the Strings properties. How would it be possible to change the actual String class in any way by only extending it ?

非常感谢您的回答

推荐答案

好吧,一个问题是,如果可以继承String类,则很可能会以多种方式破坏jvm的安全性.许多权限会检查各种String值,以确定是否允许给定的操作.如果您的代码提供了字符串值,则可以返回一个String实例,当安全管理器查看它时,该实例签出",但以后的行为就像一个完全不同的值.

Well, one problem is that you can most likely subvert the security of the jvm in a myriad of ways if you can subclass the String class. Many of the permissions check various String value to determine whether or not a given action is allowed. if your code is supplying the string values, then you can return a String instance that "checks out" when the security manager looks at it, but later acts like a completely different value.

例如,假设您具有一些敏感的jvm范围的配置:

example, say you have some sensitive jvm-wide configuration:

public static void registerProvider(String providerName, Provider impl) {
  SecurityManager sm = ...;
  if(sm != null) {
    // say the check provider method doesn't allow strings starting with "com.sun."
    sm.checkProvider(providerName);
  }
  _providerMap.put(providerName, impl);
}

现在,我实现了一个自定义String,如果传递了值"com.sun.",它会覆盖startsWith()方法以返回false,但是我的String 的实际值确实是com.sun.开头

Now, i implement a custom String which overrides the startsWith() method to return false if passed the value "com.sun.", but the actual value of my String does start with com.sun..

当然,更不用说字符串的不可变性了,如果它被破坏,可能会引起各种各样的普遍破坏(在其他答案中有更详细的说明).

Not to mention, of course, the general expectation of Strings being immutable which, if broken, could cause all kinds of general havoc (as mentioned in more detail in other answers).

这篇关于Java继承,扩展类如何影响实际的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆