0

Can we override all the methods of String class in our class by extending String class?

2
  • 4
    What is your problem that you want to override the String method? Commented May 16, 2012 at 6:35
  • 2
    Did it ever occur to you to try it? Commented May 16, 2012 at 8:08

6 Answers 6

12

String is final class you can't extend it

You also might be interested to know why it is final and why you can't extend it, The core reason is its immutability


See

Sign up to request clarification or add additional context in comments.

Comments

4

No. String is final and therefore cannot be extended.

Comments

2

You cannot do that as String class is Final.

Comments

1

I did not understand why you want to override String methods.

You can not do it as String class is final.

but you can add extra functionality to String methods by using composition like below

public class Example{
private String str;
public Example(String str){
    this.str=str;
}
public int length(){
    return str.length()+1;
}

Comments

0

You can't override final classes, of which String is one.

You can, though, create your own class with String helper functions.

e.g.,

public class StringHelper
{
    public static String DoSomethingHelpfulToAString(String stringToDoStuffTo)
    {
        return "This string is now helpful";
    }
}

then, just use the helper function on your string:

string stringToModify = "blah";
string modifiedString = StringHelper.DoSomethingHelpfulToAString(stringToModify);

Comments

0

String is a final class and thus you can't have another class extend it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.