The System.out.println () method is familiar to console output, such as SYSTEM.OUT.PRINTLN ("abc"), which outputs the string "ABC". But what happens when System.out.println () passes a parameter that is an object? Let's look at a simple example:
Copy Code code as follows:
Package test;
Class a{
int A;
int b;
public int Geta () {
return A;
}
public void SetA (int a) {
THIS.A = A;
}
public int Getb () {
return b;
}
public void Setb (int b) {
this.b = b;
}
}
public class Test {
public static void Main (String args[]) {
A A = new A ();
A.seta (8);
A.SETB (9);
System.out.println ("A.A:" +A.A);
System.out.println ("A.B:" +a.b);
System.out.println (a);
}
}
The results of the operation are:
Copy Code code as follows:
A.a:8
A.b:9
Test. A@15093f1
As you can see, I was trying to output the values of a and B, but the third line of the result was not the result we wanted. Why, then?
Object has a method of ToString (), but unfortunately we need to rewrite this method in order to output according to our own will, the above program slightly modified, that is, add rewrite the ToString function code:
Copy Code code as follows:
Package test;
Class a{
int A;
int b;
public int Geta () {
return A;
}
public void SetA (int a) {
THIS.A = A;
}
public int Getb () {
return b;
}
public void Setb (int b) {
this.b = b;
}
Public String toString () {
Return "A.A:" +a+ "; A.B: "+B;
}
}
public class Test {
public static void Main (String args[]) {
A A = new A ();
A.seta (8);
A.SETB (9);
System.out.println ("A.A:" +A.A);
System.out.println ("A.B:" +a.b);
System.out.println (a);
}
}
The results of the run are:
Copy Code code as follows: