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

后端 未结 15 2306
再見小時候
再見小時候 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 07:12

    The Java String class is a final, making it immutable. This is for efficiency reasons and that it would be extremely difficult to logically extend without error; the implementers have therefore chosen to make it a final class meaning it cannot be extended with inheritance.

    The functionality you wish your class to support is not properly part of the regular responsibilities of a String as per the single responsibility principle, a namespace it is a different abstraction, it is more specialised. You should therefore define a new class, which includes String a member and supports the methods you need to provide the namespace management you require.

    Do not be afraid to add abstractions (classes) these are the essence of good OO design.

    Try using a class responsibility collaboration (CRC) card to clarify the abstraction you need.

提交回复
热议问题