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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值