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

后端 未结 15 2309
再見小時候
再見小時候 2020-11-27 06:36

I\'d like to add a method AddDefaultNamespace() to the String class in Java so that I can type \"myString\".AddDefaultNamespace() instead of

15条回答
  •  囚心锁ツ
    2020-11-27 06:58

    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.

提交回复
热议问题