jk said:
Hello:
I want to extend the String class. That in itself is not the
problem. What I want to do is to be able to call my
extension in the same manner that Strings can be called
in Java. How can I do this.
eg:
...
"ABC".myMethod();
...
class MyString extends String {
...
public void myMethod() { ... }
...
}
As other posters have indicated you can't create subclasses of
'java.lang.String' [because it is a 'final class]. However, you *can* create
a class having 'String'-like functionality, and can even use a
'java.lang.String' object to do much of the work for you:
public class MyStrClass
{
...
private java.lang.String s;
...
// Use 's' to store your 'string data'
public MyStrClass(String s) { this.s = s; }
...
// ... various methods calling on 's' to perform tasks
...
public MyStrClass append(MyStrClass msc)
{
...
}
...
}
This is an example of using composition, that is, building a new class by
assembling together object(s) of other classes as members / attributes; you
would:
* Implement 'public' methods offering various client services
* Use these internal objects to help you perform these
advertised services
The point to grasp is that you don't have to use inheritance to obtain
extended functionality; rather, it is something best reserved for designs
where subclassing is mandatory.
Also, if it hasn't already occurred to you, if you override your new class's
'toString' method, you will be able to use it in contexts, such as the
following:
MyStrClass mc = new MyStrClass("...");
System.out.println("Your string is: " + mc);
where a 'java.lang.String' object is expected, something you can do with any
new class you create [since all classes descend from 'java.lang.Object',
thus have a 'toString' method].
I hope this helps.
Anthony Borla