Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance, how does a extending a class effect the actual class

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

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

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 ?

Thank you very much for your answers

like image 762
drlobo Avatar asked Mar 01 '13 19:03

drlobo


2 Answers

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.

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);
}

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).

like image 80
jtahlborn Avatar answered Sep 21 '22 13:09

jtahlborn


Extending a class does not affect the base class. However, it might affect the consumers of the base class.

So, let's say that you were able to extend String, you could write something like the following:

class MyString extends String {

    @Override
    public int length() {
        System.exit();
    }
}

Now you pass this class to anything that uses a string, and chances are that you would quickly exit the program. Not the end of civilization, but there are somewhat more sinister things that you could do.

like image 36
parsifal Avatar answered Sep 21 '22 13:09

parsifal