Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - Why must I override toString method instead of just creating another method?

Is there anything special about toString that makes it unique and more useful to Override compared to just leaving the toString method alone and create a separate method.

For example the following codes. What is the advantage/ disadvantage to Override toString method? Both the methods returns the same output.

@Override
public String toString(){ 
    return String.format("%s is a %s", "Apple", "fruit.");
}

public String newMethod(){
    return String.format("%s is a %s", "Apple", "fruit.");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should do it for 2 main reasons (there may be more):

  1. It's a convention. By adhering to a convention, other users of you class will instinctively know how to use them. For example, if I wanted a string representation of a class that you built, my first thought would be to call toString on it. I would never think of calling a custom method for this.

  2. Framework classes were built with this in mind. For example, System.out.println(myObj) will call ToString on myObj.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...