应该不会报错,你报什么错了?this 表示当前对象this.s 表示当前对象自己类中的那个成员变量,没有 this. 的那个 s 是构造方法中传进去的形式参数因为类中有个成员变量叫 s,构造方法的参数中的形式参数变量名也叫 s,所以就只能通过这种方法来区分哦。
你看看这段代码或许就能明白了public class TimerTest {
public void test(TimerTest t) { System.out.println(t == this); } public static void main(String[] args) { TimerTest t = new TimerTest(); t.test(t); } }
public class Temp { String s = "Hello"; public Temp(String s ) { System.out.println("s="+s); System.out.println("1->this.s="+this.s); this.s = s; System.out.println("2->this.s="+this.s); } public static void main(String[] args) { new Temp("HelloWorld!"); } } 运行结果 s=HelloWorld! 1->this.s=Hello 2->this.s=HelloWorld! 首先你定义类没有加public 一个程序必须有public的类 而且只能有一个 "s="+s; 当前的这个s 是通过构造函数传进来的s 也就是 Temp(String s )通过主方法传进来的s,也就是HelloWorld "1->this.s="+this.s 加了this. 意思是当前类对象中的s ,也就是你在类定义中的String s = "Hello";所以你获得了当前对象的属性值 this.s = s; 是把你传进来的这个s传给了String s = "Hello"的这个s 2->this.s="+this.s 由于上一步操作,在调用this.s的时候 s就变成了HelloWorld!
public class Temp { String s = "Hello"; public Temp(String s ) { System.out.println("s="+s); System.out.println("1->this.s="+this.s); this.s = s; System.out.println("2->this.s="+this.s); } public static void main(String[] args) { new Temp("HelloWorld!"); } }
public void test(TimerTest t) {
System.out.println(t == this);
} public static void main(String[] args) {
TimerTest t = new TimerTest();
t.test(t);
}
}
public class Temp
{
String s = "Hello"; public Temp(String s )
{
System.out.println("s="+s);
System.out.println("1->this.s="+this.s);
this.s = s;
System.out.println("2->this.s="+this.s);
} public static void main(String[] args)
{
new Temp("HelloWorld!");
}
}
运行结果
s=HelloWorld!
1->this.s=Hello
2->this.s=HelloWorld!
首先你定义类没有加public 一个程序必须有public的类 而且只能有一个
"s="+s; 当前的这个s 是通过构造函数传进来的s 也就是 Temp(String s )通过主方法传进来的s,也就是HelloWorld
"1->this.s="+this.s 加了this. 意思是当前类对象中的s ,也就是你在类定义中的String s = "Hello";所以你获得了当前对象的属性值
this.s = s; 是把你传进来的这个s传给了String s = "Hello"的这个s
2->this.s="+this.s 由于上一步操作,在调用this.s的时候 s就变成了HelloWorld!
public class Temp
{
String s = "Hello"; public Temp(String s )
{
System.out.println("s="+s);
System.out.println("1->this.s="+this.s);
this.s = s;
System.out.println("2->this.s="+this.s);
} public static void main(String[] args)
{
new Temp("HelloWorld!");
}
}