8

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

drlobo
  • 2,139
  • 5
  • 32
  • 42
  • 2
    sounds a bit hyperbolic – mre Mar 01 '13 at 19:47
  • @mre yeah but pretty awesomely so given it's in the certification exam! – sharakan Mar 01 '13 at 19:47
  • 2
    @drlobo I think you should change the title of this question to: "Why does the Sun Certification study guide think that extending the String class will cause civilization to collapse?" – sharakan Mar 01 '13 at 19:49
  • possible duplicate of [Good reasons to prohibit inheritance in Java?](http://stackoverflow.com/questions/218744/good-reasons-to-prohibit-inheritance-in-java) – Has QUIT--Anony-Mousse Mar 01 '13 at 19:53

6 Answers6

6

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

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • Would you call this `ChuckNorrisString`? :-) – kdgregory Mar 02 '13 at 01:37
  • Although, as I think about it, `ChuckNorrisString` would override `hashCode()`: you put it in a map, and when you go back later to look for it, it's not there. – kdgregory Mar 02 '13 at 01:38
  • @kdgregory - a ChuckNorrisString wouldn't be very useful because it would never be equal to anything. and sorting it would be difficult because it would always be greater than everything else. – jtahlborn Mar 02 '13 at 03:24
  • Well-played. (did you know that whitespace can't be used to fill out the 15-character minimum comment length?) – kdgregory Mar 02 '13 at 13:01
4

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.

parsifal
  • 529
  • 2
  • 4
2

Consider that throughout the Java API, you will see constructs such as:

HashMap<String, Object> map;

which use Strings for indexing. A very common thing, e.g. for properties and - and that probably is worst in security relevant places. This code relies on an unmodified String to remain secure.

But now let your modified String class allow e.g. reversing strings in-place.

Then world as we know it would collapse, because all over the place maps would become a crazy mess. Logging would break down, etc.

A lot of code relies on the String class to be immutable, and well, if it is truly immutable, what functionality could you want to add on to it anyway?

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • Changing the behaviour must not invalidate an immutability constraint. Think of a class `ReversedString` with a convenient constructor. – Jens Piegsa Mar 01 '13 at 19:59
  • @jeppi you could do this out of place trivially with a static method, without the need for a new class at all, actually. – Has QUIT--Anony-Mousse Mar 01 '13 at 20:31
  • In somes scenarios you prefer constructors over static factory methods. Maybe ReversedString isn't the most realistic example for that. It was just there to speak about immutable objects ... – Jens Piegsa Mar 02 '13 at 08:30
1

Extending a class does not effect the class at all. however, since any inherited class is also a base class, it should abide by the base class's contracts of behaviour. if programmers were to change common framework types, then you just could not count on those classes to work as expected. So, you want to prevent the option to abuse such classes- this is done using the final keyword

omer schleifer
  • 3,897
  • 5
  • 31
  • 42
0

The hyperbole of catastrophy is probably an allusion to security aspects of String's (im)mutability. A string is often passed as a parameter to various I/O resource connection APIs (e.g. JDBC and File I/O). Such a string if often either a concatenation of resource locators and authentication credentials and that API will perform a check to make sure that the credentials are valid for the requested resource before returning the connection. If String were mutable, it would open gateway for all kinds of security breaches as the resource pointer/address (such as for example a database name for DB connection or file name containing sensitive info for a user) could be modified after the authentication was successful but before the resource connection is established for the original resource requested, resulting in unauthorized access and subverting access control.

Another reason for making String immutable is to make it thread-safe.

amphibient
  • 29,770
  • 54
  • 146
  • 240
0

Actually the problem isn't anything to do with just extending String or any other class for that matter.

The problem is actually with Java itself. The problem is that you cannot actually define in its code the contract that a particular object implements. It is not actually stated in the code for String that it is immutable because immutability cannot be specified, it can only be coded. That contract only arises from the actual implementation of String.

If it was possible to state in the Java language that String and Number and Integer etc. are immutable then we would not need to make these classes final. In my opinion this is a debilitating disease of Java that you cannot define the contract in code. You can only code it and document it.

I would love to be able to extend string and define, perhaps, an UppercaseString extends String but there is not a contract(immutable,interned) keyword in Java so I cannot do so because to get nearest to this contract, the only keyword available is final instead of immutable as it should be.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213