Neel Neel - 4 months ago 46
Java Question

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? Please help me.

Thanks

Answer

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.

Comments