It happens that I want to print this data on the screen, which is found in the tostring method.
public String tostring() {
return "the weight is :"+ this.getWeight() +" and my age is :"+ this.getAge();
}
but it prints it this way
ejercicio2.Ejercicio2@15db9742
here the code with the set and get
public class Ejercicio2 {
private int weight;
private int age;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
and the main class
public class Usoejercicio2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ejercicio2 ob1 = new Ejercicio2();
ob1.setAge(21);
ob1.setWeight(55);
System.out.println(ob1);
what am I doing wrong? yes please correct me
The problem lies in the way you have written the name of this method:
If you had used the annotation
@Override
, the compiler would have given a compilation error and this is becausetostring()
it is not a method inherited from the classObject
(base class of all classes in Java), therefore it cannot be overridden.Error example:
When compiling it shows the following error:
The error means that you cannot override the method because there is no base class that has it implemented.
The method that all classes inherit (because by default they are subclasses of
Object
) is calledtoString
and nottostring
. So the solution is to rename it:And that's it, the program should launch the expected result.
I also emphasize that this sentence:
It is equivalent to:
The difference is that in the first statement, the Java compiler implicitly calls the method
toString()
and in the second we add it manually. So it doesn't matter which one you use, because both will give the same result.Conclusion:
Use the annotation
@Override
, it saves headaches.