读书人

一个奇怪的有关问题

发布时间: 2012-03-13 11:21:12 作者: rapoo

一个奇怪的问题,……


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方法,来判别对象是否相等。

读书人网 >J2SE开发

热点推荐