Hi
Can anyone recognise if this is a valid toString method?
cheers
tom
Printable View
No.
Hint: What are you returning? What is the return type of the toString method? When you call a standard class's toString() function, does anything print out? Or do you have to print that out yourself?
No. It has to return a String.
A valid toString() method would
public String toString()
{
String str = "Tom";
return str;
}
What you're doing with yours above is basically
public void toString()
{
System.out.println("Tom");
}
Also, it depends what you mean by "valid".
Object has a toString() method that returns a String, but it makes no sense whatsoever unless you're a java compiler (like Eclipse). Also, since Object has a toString(), unless you overload it, you have to have the same parameters, in this case none.
All classes have Object's toString() in them by default and keep it as theirs unless they override it with their own.
An ArrayList will return a toString like this:
[item one, item two, item three, ... last item]
However, it will again make sense only for classes that have a "nice" toString(), like String or Integer for example, otherwise it'll probably use Object's toString(). Overloading is for when you want to have a different parameter, but still have the same return type.
For instance:
public String toString(String example)
{
return example;
}
or
public String toString(String secondExample)
{
String str = "bob " + secondExample;
return str;
}
Also, for a toString(), often people use them for things like:
public String toString()
{
String str = "The value is: " + getValue() + ". The name of this item is: " + getName() + ".";
// be careful to use getValue() and getName() and other get methods instead of
// having String str = "The value is: " + value + ". The name of this item is: " + name + ".";
// that may not always produce what you want
// also, make sure that if you have a get method, you call a setMethod() either in your constructor
// or in this toString() method. If in the toString() method itself, make sure to have the value you're
// passing it as a parameter, set Methods have at least 1, sometimes more, parameters, is defined somehow
// inside the method or else it'll say "cannot find symbol". Also, if you don't call the set method, your
// toString() will return "null" for all the get Methods that never called a set method.
return str;
}