<pre class="line mt-5 q-content" style="padding: 0px; color: rgb(51, 51, 51); line-height: 20px; font-family: arial, 'courier new', courier, 宋体, monospace, 'Microsoft YaHei'; font-size: 14px; margin-top: 8px; margin-bottom: 0px; white-space: pre-wrap; -ms-word-break: break-all; -ms-word-wrap: break-word;" name="code">原文地址<a target=_blank style="color: rgb(51, 102, 153); text-decoration: none;" href="http://zhidao.baidu.com/link?url=Nr36RpY2CGJsqauG3yF22UIXJQIgFdt7Ipy6dJPVZYT43mCXYIL4ui3I4LXY3Nb3F8VSCmbOBVLJTxkvV6X8cqhttp://" target="_blank">点击打开链接</a>
</pre><pre class="line mt-5 q-content" style="padding: 0px; color: rgb(51, 51, 51); line-height: 20px; font-family: arial, 'courier new', courier, 宋体, monospace, 'Microsoft YaHei'; font-size: 14px; margin-top: 8px; margin-bottom: 0px; white-space: pre-wrap; -ms-word-break: break-all; -ms-word-wrap: break-word;" name="code">public class Threadtest2 extends Thread{ private int c=5; private static int no; public Threadtest2(){ start(); } public void run(){ for(int i=0;i<10;i++){ System.out.println(this); } } 请问,这个this 指代什么呢?JAVA初学者。不甚了解!
如果我再重写toString方法 public String toString(){ return getName(); } 这个this会调用toString方法,不知道为什么
</pre><pre class="best-text mb-10" id="best-content-284723486" style="padding: 0px; color: rgb(51, 51, 51); line-height: 24px; font-family: arial, 'courier new', courier, 宋体, monospace, 'Microsoft YaHei'; font-size: 14px; margin-top: 0px; margin-bottom: 10px; white-space: pre-wrap; -ms-word-wrap: break-word; background-color: rgb(243, 255, 236);" name="code">this表示当前对象,你使用System.out.println(this)就是表示打印当前对象,而输出的时候,因为this的类型并不是字符串,因此打印时会调用默认的toString方法。你重写了toString方法,自然打印出来的就是你重写的toString方法里面的语句: return getName(); 也就是说,最终调用了getName()方法,那么System.out.println(this)实际运行时等同于:System.out.println(getName());
除了楼上几位说的以外,toString是从Object类继承来的方法,Object是所有类的父类,所以所有的类都有该方法。你的那个类的this自然就有这个方法了,另外像hashCode() equals finalize clone 这些都是Object类的方法,任何的类都会有这么方法的。
toString
public String toString()返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象 哈希码 的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:
getClass().getName() + '@' + Integer.toHexString(hashCode())
-
顶
- 1