简体   繁体   中英

Can I create toString() of a specific method? Not the whole class

I have a class named MyString{} . I have created a method like this

MyString replaceAll(char oldChar, char newChar){

}

The method replace a char array by the oldChar and newChar. I have some other methods like upper one. But I want it, when this method is called it should return an object and that object will print the replaced array. I cant change my method type like

String replaceAll(char oldChar, char newChar){

}

Can I make toString method only for my methods? Is it possible?

No, a method belongs to a type , not another method.

It's not at all clear what you're trying to achieve, but it sounds like you just need to override toString() within MyString . Then when you call:

MyString x = new MyString(...);
String foo = x.replaceAll('x', 'y').toString();

that will call toString() on the MyString reference returned by replaceAll ... which will presumably have all the appropriate char values replaced.

If that doesn't help, please clarify your question as it's pretty unclear at the moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM