【发布时间】:2014-02-02 00:28:43
【问题描述】:
我有两个类,ThisTest 和 SimpleTime。 buildString() 方法返回一个带有“this”关键字的连接字符串。当我运行它时,“this”似乎是指 toString() 方法而不是 SimpleTime 类。为什么我使用“this”关键字时会执行 toString() 方法?谢谢。
import java.text.DecimalFormat;
import javax.swing.*;
public class ThisTest {
public static void main(String args[]) {
SimpleTime time = new SimpleTime( 12, 30, 19 );
JOptionPane.showMessageDialog( null, time.buildString(),
"Demonstrating the \"this\" Reference", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
class SimpleTime {
private int hour, minute, second;
public SimpleTime( int hour, int minute, int second )
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public String buildString()
{
return "this.toString(): " + this.toString() +
"\ntoString(): " + toString() +
"\nthis (with implicit toString() call): " + this;
}
public String toString()
{
DecimalFormat twoDigits = new DecimalFormat("00");
//"this" not required, because toString does not have
//local variables with same names as instance variables
return twoDigits.format( this.hour ) + ":" +
twoDigits.format( this.minute ) + ":" +
twoDigits.format( this.second );
}
public String anotherString()
{
return "Another String for you";
}
}
【问题讨论】:
-
你知道
this是什么吗?你知道String连接吗? -
您期望发生什么?
-
我了解字符串连接的作用以及“this”是什么,但我不明白为什么在使用“this”时会调用 toString。
-
我真的不知道会发生什么
标签: java methods this tostring implicit