0

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

Sujith Menon
  • 11
  • 1
  • 1
  • 2

6 Answers6

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
4

No. String is final and therefore cannot be extended.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

You cannot do that as String class is Final.

UVM
  • 9,776
  • 6
  • 41
  • 66
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;
}
Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
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);
Tass
  • 1,238
  • 11
  • 21
0

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

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250