Here is some background information on toString:
The toString method is supposed to return a String representing the
state of the object. It is defined as a method on class Object, from
which all other classes are derived. So toString reliably exists as a
method on every object.
There is some magic involving toString. When you pass your Elevator
object to println, it invokes Elevator.toString automatically to get
the printable string. So instead of
String s = myElevator.toString();
System.out.println(s);
You can write simply
System.out.println(myElevator);
It is important to understand why this works. Every class, by virtue
of being implicitly derived from class Object, has a toString method.
The default implementation, declared in class Object, is not really
useful -- it produces a string containing the class name and a hash
code. That's why you need to override it in your class, to produce a
printable representation of the state of the Elevator object.
Println always invokes toString on whatever object is passed to it.
Since your class overrides toString, it is your version of that method
that is called.
You can put any information you want into the String returned by
toString. For example, you if you had fields floornumber and
npassengers, you could write toString like this:
public String toString() {
return "Elevator is at floor " + floornumber + " and contains "
+ npassengers + " passengers.";
}
toString should never take any arguments. If you define it to take
arguments, the type signature of your method doesn't match up with the
one println is looking for. Since toString is a nonstatic method of
your class it already has object scope access to all the data fields
of the Elevator object. So there's no need to pass the Elevator
object to it as an argument.