A Java instance that converts an object to a string _java

Source: Internet
Author: User

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:

A.a:8
A.b:9
A.a:8; A.b:9

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.