Can I add new methods to the String class in Java?

String is a final class which means it cannot be extended to work on your own implementation.


Well, actually everyone is being unimaginative. I needed to write my own version of startsWith method because I needed one that was case insensitive.

class MyString{
    public String str;
    public MyString(String str){
        this.str = str;
    }
    // Your methods.
}

Then it's quite simple, you make your String as such:

MyString StringOne = new MyString("Stringy stuff");

and when you need to call a method in the String library, simple do so like this:

StringOne.str.equals("");

or something similar, and there you have it...extending of the String class.

Tags:

Java

String