Every class of Java extends Object class, thus all methods available in Object class are accessible in Java class by default. One of the methods is toString(), example as below:
Line 1: class Pizza {
Line 2: String name;
Line 3: double price;
Line 4: }
Line 5: public static void main(String args[]) {
Line 6: Pizza pizzaObj = new Pizza();
Line 7: pizzaObj.name = "Veggie Pizza";
Line 8: pizzaObj.price = 250;
Line 9: System.out.println(pizzaObj); //Pizza@7ad041f3
Line 10: }
Every time we try to print the object, by default behind the scene it will call pizzaObj.toString() on Line 9 even if we don't mention and print "Pizza@7ad041f3"
We do not have any methods named toString() in Pizza class, but we do have toString() in Object Class which is always a parent of Java class and thus accessible to Pizza class as well
toString() - return getClass().getName() + '@' + Integer.toHexString(hashCode())
getClass() -> gets the Pizza class
getName() -> Pizza //Pizza
@ -> Adds it after the className //Pizza@
Integer.toHexString(hashcode()) -> Hashcode is generated based on the values we have and it tries to create a small string out of all the data that we have using Hash algorithm of fixed size.
toHexString(hashcode) returns an integer format of hashcode hexstring out of the toString() method as a result
When we override the toString() and return the string of our choice, the next time we print the object, we would be able to print the object in desired manner.
In our example, Line 9 prints Pizza@7ad041f3, which is nothing but the default behavior of the toString(), in order to print "Veggie Pizza : 250" while printing your object, method can be overridden as below(Line 5 - Line 8)
Line 1: class Pizza {
Line 2: String name;
Line 3: double price;
Line 4: }
Line 5: @Override
Line 6: public String toString() {
Line 7: return name + " : " + price;
Line 8: }
Line 9: public static void main(String args[]) {
Line 10: Pizza pizzaObj = new Pizza();
Line 11: pizzaObj.name = "Veggie Pizza";
Line 12: pizzaObj.price = 250;
Line 13: System.out.println(pizzaObj); //Veggie Pizza : 250
Line 14:}
How do you create a toString method in Java?
The toString method already exists in all classes in Java as it’s there in the parent class. So, there’s no need to create it, but you can override the method as per your requirement.
In the nutshell, toString() method allows to override the default output string and return the string representation of class object in desired manner, which is used while printing an object.
Opmerkingen