6

This is mainly out of curiosity. How would you (if you can) make a class that mimics String. You can't extend String as it's final so that's a no go, but purely for the interest factor, I thought about creating an object that could be initialized literally (String s = "string";).

Is this possible? If so, how? If not, why?

1
  • 1
    Side note: I recently created my own wrapper class around string; just to have something that plays nicely with unit tests (as you figured - String is final; so you can't create mock objects for String.class); but in the end I decided that the gain is not worth the trouble. Commented May 5, 2015 at 12:09

2 Answers 2

7

No, it's not possible to introduce your own literal types in Java. The language specification gives the syntax for numeric, character and string literals, and that's it.

You can't even add your own implicit conversions from an existing type with a literal representation to your own custom types (as you can in C# - as an example of a "close cousin) to Java.

Sign up to request clarification or add additional context in comments.

Comments

4

String is Final, for security reasons.

However, as of Java 1.4, String has been an implementation of the CharSequence interface. If you write your code in terms of CharSequences, you will be able to run it against any implementation of that interface, String included.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.