我用Eclipse创建了个java project后Add一个包(方法覆盖程序举例).在里面加个OverrideExample.java输入书上的代码.package 方法覆盖程序举例;import java.awt.*;
import java.applet.Applet;
class aaa
{
double f(double x,double y)
{
return x*y;
}
}
class bbb extends aaa
{
double f(double x,double y)
{
return x+y;
}
}
public class OverrideExample extends Applet
{
bbb obj;
public void init()
{
obj=new bbb();
}
public void paint(Graphics g)
{
g.drawString("the object is "+obj.toString(),5,20);
g.drawString("the program's output is "+obj.f(4,6),5,40);
}
}输出结果是:
the object is 方法覆盖程序举例.bbb@e4f972
the program's output is 10.0
书上的结果是:
the object is 方法覆盖程序举例.bbb@a6d511
the program's output is 10.0
其他的我明白,类名后面跟个"@e4f972"或"@a6d511"是什么意思?
import java.applet.Applet;
class aaa
{
double f(double x,double y)
{
return x*y;
}
}
class bbb extends aaa
{
double f(double x,double y)
{
return x+y;
}
}
public class OverrideExample extends Applet
{
bbb obj;
public void init()
{
obj=new bbb();
}
public void paint(Graphics g)
{
g.drawString("the object is "+obj.toString(),5,20);
g.drawString("the program's output is "+obj.f(4,6),5,40);
}
}输出结果是:
the object is 方法覆盖程序举例.bbb@e4f972
the program's output is 10.0
书上的结果是:
the object is 方法覆盖程序举例.bbb@a6d511
the program's output is 10.0
其他的我明白,类名后面跟个"@e4f972"或"@a6d511"是什么意思?
你如果只想显示类名,就自己重写toString方法!如:
public String toString()
{
return "aaa";
}
没错 这个地址 叫 哈希码,表示这个对象在内存中的地址这是object默认的to String 方法
你可以重写它
你如果只想显示类名,就自己重写toString方法! 如:
public String toString()
{
return "aaa";
}
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
所以可以自己充血toString()方法:
public String toString(){
return ""; //可以返回对象的属性值
}