How to create a String class replica?

From your question it sounds like the thing you are looking for is simple delegation:

class MyString {

  String delegate; // The actual string you delegate to from your class

  public MyString(String delegate) {
    this.delegate = delegate; // Assign the string that backs your class
  }

  int length() {
    return delegate.length(); // Delegate the method call to the string
  }

  // other methods that delegate to the string field
}

Going through the various answers here, and the askers updates and clarifications, it appears that what the asker wants is a class that looks, smells and sounds like a String, but is not.

That is they would like to be able to do:

MyString string = "String!!";

This cannot work, since java.lang.String is a final class, and so every "String" that the compiler produces will be a java.lang.String object, since this is not a MyString object they cannot be assigned to each other.

In weakly typed languages you would be able to create such a class, since if a class looks, smells and sounds like a duck, then to all intents and purposes, it is a duck. Java, however, is a strongly typed language, and a duck is only a duck if it happens to be from the Anatidae family of birds.


Since final classes cannot be subclassed, create a new class that has a String instance inside and operate on this object.

public class MyString {
  private String s;

  public MyString( String s ) {
    setInternalString( s );
  }

  public int myLength() {
    return getInternalString().length();
  }

  private void setInternalString( String s ) {
    this.s = s;
  }

  private String getInternalString() {
    return this.s == null ? "" : this.s;
  }
}

Tags:

Java

String