Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Class that extends String (or similar)

Tags:

java

class

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?

like image 809
Spedwards Avatar asked May 05 '15 12:05

Spedwards


Video Answer


2 Answers

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.

like image 149
Jon Skeet Avatar answered Nov 07 '22 07:11

Jon Skeet


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.

like image 32
keshlam Avatar answered Nov 07 '22 06:11

keshlam