public class Solution { public static void main(String[] args) { Cat cat2 = new Cat("Barsik", 3, 3, 3); System.out.println(cat2); } public static class Cat{ public static int count = 0; private String name; private int age; private int weight; private int strength; public Cat(String name, int age, int weight, int strength) { count++; this.name = name; this.age = age; this.weight = weight; this.strength = strength; // public String toString() { return name; } } } } - I understand that you commented out toString should be uncommented and removed from the constructor (how did it get there at all ??) - carapuz
- And what is displayed now is the result of the work of toString from the Object class, which is implemented as getClass (). GetName () + '@' + Integer.toHexString (hashCode ()) - carapuz
2 answers
Output operators, for example println implicitly call the object's toString method (it is present in all objects). This method serves to represent an object as a string.
Each class has its own implementation of the method. For example, Integer following code:
public static String toString(int i, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; /* Use the faster version */ if (radix == 10) { return toString(i); } char buf[] = new char[33]; boolean negative = (i < 0); int charPos = 32; if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[-(i % radix)]; i = i / radix; } buf[charPos] = digits[-i]; if (negative) { buf[--charPos] = '-'; } return new String(buf, charPos, (33 - charPos)); } As you can see, the method returns a string (roughly) return new String(buf, charPos, (33 - charPos));
Other classes have the same thing. It can be implemented in any class. You can write anything there, even return "hello, world"; And this very System.out.println implicitly calls this object's toString method on the object and displays this same "hello, world".
By default for an object, if you do not override the toString() method, it will lead us to the java.lang.Object.toString method (since Cat is an object and implicitly, as it were, the heir of the java.lang.Object class) The default string in the ToString() method is:
getClass().getName() + '@' + Integer.toHexString(hashCode())
which you just see.
proof :-)
As a consequence, in order to see something human when outputting an object using output operators, you need to define some logic in the toString() method toString()
In your case, you just need to uncomment this method and remove it from the constructor (because how did you find the method inside the constructor is incomprehensible to me).
public static class Cat { ... // объявление полей ... public Cat(String name, int age, int weight, int strength) { ... // некая логика конструктора ... } // волшебный метод, который превращает объект не в непонятные символы, // а в нечто человекочетаемое и симпатичное глазу public String toString() { return name; } } When recording
Cat cat2 = new Cat("Barsik", 3, 3, 3); System.out.println(cat2); he will output Barsik
- Thank you for the detailed and (in my opinion) brilliant answer. And how to make that would deduce not only Barsik, but also other parameters? And is it possible to do without this worthy method? I may be wrong, I think that the toString () method is extreme or something ... - Shaukat
- @ Shauk you can write whatever you want in this method. You can write
return "Имя: " + name + ",\n Возраст: " + age + ",\n Вес: " + weight;If exaggerated, it would be the same as creating an extrashowInfo()method in which it would be written:System.out.println("Имя: " + name);System.out.println("Возраст: " + age);System.out.println("Вес: " + weight);........ normal method. Not for nothing is it available for all of all objects in Java) - Alexey Shimansky - Now, I found in your answer what I was looking for. Thank you again. Life is cheerful). - Shaukat
- @ Shaukat is strange, my answer is exactly what is needed, but another was noted to be faithful)) appreciated the humor)) - Alexey Shimansky
- I apologize, I missed.) - Shaukat
Uncomment the line public String toString () Your code:
public class Solution { public static void main(String[] args) { Cat cat2 = new Cat("Barsik", 3, 3, 3); System.out.println(cat2); } public static class Cat { public static int count = 0; private String name; private int age; private int weight; private int strength; public Cat(String name, int age, int weight, int strength) { count++; this.name = name; this.age = age; this.weight = weight; this.strength = strength; } public String toString() { return name; } } }