| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 819 人关注过本帖
标题:toString方法有点不懂.
只看楼主 加入收藏
heilong
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:777
专家分:0
注 册:2007-6-7
收藏
 问题点数:0 回复次数:6 
toString方法有点不懂.
class Soap
{
private String s;
private String t;
Soap()
{
System.out.println("Soap()");
s = new String("Constructed");
t = new String("hello");
}
public String toString() { return t; }
}
public class Bath
{
Soap castille;
Bath()
{
castille=new Soap();
}
void print()
{
System.out.println("castille = " + castille);
}
public static void main(String[] args)
{
Bath b = new Bath();
b.print();
}
}
是不是每个类的对象都有个toString方法
我上面的方法,是不是重定了那个toString方法.打印出来的是castille=hello;还有为什么会自动调用toString方法?
如果把上面的方法去掉,打印出的是 Soap@c17164 这个是对象是什么啊?
默认的toString方法里面返回的是什么,还是void???????????

[此贴子已经被作者于2007-6-29 17:15:14编辑过]

搜索更多相关主题的帖子: toString 
2007-06-29 16:56
TS_星光绝灭
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2007-6-28
收藏
得分:0 
上面是你的完整程序吗?castille没有定义额?
对于toString()是从Object中继承下来的,当然你也可以覆盖,他返回的String类型,
是关于该类的信息之类的

黯淡,但矜持
2007-06-29 17:08
heilong
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:777
专家分:0
注 册:2007-6-7
收藏
得分:0 
不好意思,一时大意,给写少了.就不明白为什么会自动调用,还有后面是对象的什么信息?

风水鸡蛋壳,财去人安乐!----->
2007-06-29 17:11
heilong
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:777
专家分:0
注 册:2007-6-7
收藏
得分:0 
还有如果把
Bath()
{
castille=new Soap();
}
构造方法去掉,castille为null;这又是为什么呢?

风水鸡蛋壳,财去人安乐!----->
2007-06-29 17:26
TS_星光绝灭
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2007-6-28
收藏
得分:0 

System.out.print();中的参数是对象时会自动调用对象的toString()方法
以下是在JDK1.6文档中的注释
public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Returns:
a string representation of the object.


黯淡,但矜持
2007-06-29 17:33
TS_星光绝灭
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2007-6-28
收藏
得分:0 
Soap@c17164 这里c17164应该就是上面所说的Soap的hashCode,

黯淡,但矜持
2007-06-29 17:37
heilong
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:777
专家分:0
注 册:2007-6-7
收藏
得分:0 
谢谢啊,我还是看看API文档,英语不好.

风水鸡蛋壳,财去人安乐!----->
2007-06-29 17:42
快速回复:toString方法有点不懂.
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011915 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved