Can we override all the methods of String class in our class by extending String class?
Asked
Active
Viewed 1.1k times
0
-
4What is your problem that you want to override the String method? – Crazenezz May 16 '12 at 06:35
-
2Did it ever occur to you to ***try it?*** – Andrew Thompson May 16 '12 at 08:08
6 Answers
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