Converts an object to a Java instance of a string

  • 2020-04-01 02:38:34
  • OfStack

The system.out.println () method is familiar to us and is used for console output, such as system.out.println (" ABC "), which prints the string "ABC". But what happens when system.out.println () passes an object as an argument? Here's a simple example:


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 running result is:


a.a:8
a.b:9
test.A@15093f1

As you can see, I was going to print the values of a and b, but the third row of the result is not what we want. Why?

There is a toString() method in Object, but unfortunately we need to rewrite this method in order to output according to our own wishes. We will modify the above program slightly, that is, add the code to rewrite the toString function:


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 result of operation is:


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


Related articles: