简体   繁体   中英

Java Class that extends String (or similar)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM