日期:2014-05-20  浏览次数:20540 次

一个奇怪的问题,……


Java code

public class TV extends Machine{
    private String brand;
    private int maxvolume;
    
    public TV() {
        
    }
    public void work(){
        System.out.println("Play audio and video meida");
    }
    public String toString(){
        return "The power is "+getPower()+"\n"+"The voltage is "+getVoltage()+"\n"+"The current is "+getCurrent()+"\n"+"The type is "+getType()+"\n"+"The brand is "+brand+"\n"+"The maximum volume is "+maxvolume;
    }
    public static void main(String[] args) {
        TV tv=new TV();
        System.out.println(tv);
        
    }
}


System.out.println(tv);

为什么可以达到
System.out.println(tv.toString());
的效果?

父类Machine里面没有重写方法



------解决方案--------------------
println(Object o)自动调用类的toString,没有重写的话就是 类名@hashcode
------解决方案--------------------
这个类中重写了toString方法,来判别对象是否相等。