Print reference (object)

package reusing;
class WaterSource {
  private String s;
  WaterSource() {
    System.out.println("WaterSource()");
    s = "Constructed";
  }
 public String toString() {
//	  return getClass().getName() + "@" + Integer.toHexString(hashCode());
	  return s;
	  }
	
}
public class SprinklerSystem {
  private String valve1, valve2, valve3, valve4;
  private WaterSource source = new WaterSource();
  private int i;
  private float f;
  public String x(){
	  return "source = " + source;
  }
 public String toString() {
    return
      "valve1 = " + valve1 + " " +
      "valve2 = " + valve2 + " " +
      "valve3 = " + valve3 + " " +
      "valve4 = " + valve4 + "\n" +
      "i = " + i + " " + "f = " + f + " "
      + "source = " + source;
  }	
  public static void main(String[] args) {
	  WaterSource ss=new WaterSource();
// SprinklerSystem sprinklers = new SprinklerSystem ();
    System.out.println(ss);
    
  }
}

   Parse:

println (reference) object: the compiler calls the println method (

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

The println method calls the valueOf method, (null reference returns null) returns the toString method of the object, and calls the print method to print

public static String valueOf(Object obj) {
 return (obj == null) ? "null" : obj.toString(); }

 If there is no overridden toString method in no class, the default method is called

public String toString() {

        return getClass().getName() + "@" + Integer.toHexString(hashCode());

    }


 * If the toString method is overridden, print the return of the method


If print prints an object (reference), call the valueOf method (null reference returns null) to return the toString method of the object, and print

 public void print(Object obj) {
        write(String.valueOf(obj));
    }

/**Output:
WaterSource()  
valve1 = null valve2 = null valve3 = null valve4 = null
i = 0 f = 0.0 source = Constructed  
a
WaterSource()  
Constructed 
 * 
 */


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324439451&siteId=291194637