Print引用(对象)

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);
    
  }
} 

   解析:

println(引用)对象:编译器调用println方法(

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

println方法调用valueOf方法,(空引用则返回null)返回对象的toString方法,并调用print方法打印

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

 若无类中无重写toString方法则调用默认方法

public String toString() {

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

    }


 *  若重写toString方法则打印方法的返回


若print打印的是对象(引用),调用valueOf方法(空引用则返回null)返回对象的toString方法,并打印

 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 
 * 
 */


阅读更多

没有更多推荐了,返回首页