开发者

Overriding append method in stringBuilder?

I have a question regarding the append method in the StringBuilder class. I was asked how can we override the append() method in the StringBuilder class while stringBuilder class is final. Is the same logic applicable for overriding toString() in String class while String class is final? Plea开发者_StackOverflow社区se help me.

Thanks


No, you can't really override a final method, there might be some bytecode level magic that would allow you to do that, but I'm not sure it is worth it.

You can create a wrapper class, something like MyStringBuilder and for every one of the methods in StringBuilder create a method that delegates to an instance of StringBuilder, then you can modify the append methods as you see fit. There is a catch with this approach and that is that you can't access private variables defined in StringBuilder although that might not be such a big deal for your use case. YMMV


A class declared final can't be extended, so there is no way to override any method of it.

A class which is not declared final can be extended, but any method declared final can't be overridden.


Overriding toString in the String class is overriding a method of java.lang.Object in java.lang.String. Since the class is declared final, you can't derive from it and hence not override the toString-method, which is a special case in String, since it returns the String itself.

Overriding a method in a final class is impossible. And append () isn't a method in Object, so they are not equivalent, but you can't override append either.


Those classes are final by design. The API designers didn't want to deal with the added complexity of making those classes a base class for inheritance.

Instead of inheritance, you can use delegation and create your own StringBuilder class that uses an instance of java.lang.StringBuilder as delegate. This makes it trivial to create your own append methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜