Java: toString
toString is very useful in Java, basically it waits for a function or method to ask "Hang on ive been told to show a string, where the hell is it?", it then overrides anything else which might help with this and tells it a string.
The following shows a good example of this:
class ClassOne{
private int hour;
private int minute;
private int second;
ClassOne(int h, int m, int s){
hour = h;
minute = m;
second = s;
System.out.printf("The time is: %s\n", this);
}
public String toString(){
return String.format("%d:%d:%d", hour, minute, second);
}
};
public class Main {
public static void main(String[] args) {
ClassOne Object = new ClassOne(12, 30, 10)
}
}
In this example 12:30:10 would be outputted.
The only thing you might not understand is printf, all it does is 'print format', basically you can format stuff before printing it.
As you can see toString pretty simple, all it does is gives a string when this is refered to, this is because it knows its looking for a string, and the toString is in the same class (therefore could be refered to via 'this') so because we generalised 'this' it decides the toString is going to take over.
Also if we refer to an object as a string it will look in the class we have specified and go to the toString method.
For example:
class ClassOne{
private int hour;
private int minute;
private ClassTwo Object;
private int second;
ClassOne(int h, int m, int s){
hour = h;
minute = m;
second = s;
System.out.printf("The time is: %s\n", this);
}
public String toString(){
return String.format("%d:%d:%d", hour, minute, second);
}
};
class ClassTwo{
private String name;
private ClassOne TimeObject;
ClassTwo(String n, ClassOne Time){
name = n;
TimeObject = Time;
System.out.println(this);
}
public String toString(){
return String.format("Name:%s\nTimeBorn:%s", name, TimeObject);
}
};
public class Main {
public static void main(String[] args) {
ClassOne Object = new ClassOne(12, 10, 10);
ClassTwo Object2 = new ClassTwo("Bob", Object);
}
}
Ok lets just go through this..
Basically the ClassTwo constructor is going "Gimmie a string(name) and a ClassOne object", when we give it these it sets the variable name and the object TimeObject. Then it prints 'this', hangon a second what is 'this' supposed to mean?
It doesn't know so it goes to the toString. toString gets the first half ready to print but doesn't know how to print TimeObject as a string so it goes to ClassOne, ClassOne dosn't know either so it goes to ClassOne's toString method.
Back to Java

