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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With