简体   繁体   中英

toString(int variable, n) vs toString()

I have been looking for the answer this question everywhere and I don't know what it is called, but what is the point of a toString method with a variable in its parenthesis?

public static String toString(Student[] list, int n)
   {

   }

I cannot find this answer for some reason. I didn't know you can provide input to a toString, as I thought that you didn't call the method directly, you would just print a string whenever you declare the class it is in.

You can provide any parameters to any method, but toString is special in that it's used in a lot of the inner workings of Java.

That said...this is not that toString method. The one you wish to override takes no parameters whatsoever.

@Override
public String toString() {
    // implementation
}

A toString that takes parameters implies that the object doesn't have enough information to print about itself, which is contradictory, so this method would like be best renamed to something more appropriate.

toString() can be over ridden in your specific class,

something like

public class ToStringEg {

private Student[] list;

private int n;

public ToStringEg(Student[] list, int n) {
    super();
    this.list = list;
    this.n = n;
}

@Override
public String toString() {
    StringBuffer buf = new StringBuffer();
    // You can access list and v varible required by you
    //finally create a buf based on your logic
    return buf.toString();
}

}

toString() is just a method like anything else. It just so happens that the toString() method with no arguments gets called automatically by a lot of things, like when trying to print out an object. However, that does not prevent you from making another method named toString(int variable) . That method will never be called automatically, but you can still declare it and call it yourself if you want to do custom string manipulation in whatever program you are writing.

Your toString() method has totally different from the special method @Override public String toString() inherited from Object class.

I think you should change your method name to avoid confusion in future.

How toString() method automatically called during System.out.println() or String.valueOf(obj) ? NO MAGIC! Just see the implementation of valueOf() method in String class.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

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