1.java中this的用法
1. this指当前对象。
当在一个类中要明确指出使用对象变量或函数时加上this引用。如下面例子中:
public class Hello {
String s = "Hello";
public Hello(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) {
Hello x=new Hello("HelloWorld!");
}
}
运行结果:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
在这个例子中,构造函数Hello中,参数s与类Hello的变量s同名,这时直接对s进行操作则是对参数s进行操作。对类Hello的成员变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对构造函数中传递过来的参数s进行打印结果;
第二行是对成员变量s的打印;第三行是先对成员变量s赋传过来的参数s值后再打印,所以结果是HelloWorld!
2. this作为参数传递
当你要把自己作为参数传递给别的对象时如:
public class A {
public A() {
new B(this).print();
}
public void print() {
System.out.println("Hello from A!");
}
}
public class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}
}
运行结果:
Hello from A!
Hello from B!
在这个例子中,对象A的构造函数中,new
B(this)把对象A作为参数传递给了对象B的构造函数。
2.JAVA(this用法)
这个this肯定是用在某个类的方法里吧?呵呵,我们继续往下说。
举个例子:
public class persion{
private String name=null;
private int age;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
在这个类中setName方法中第一个变量用this是为了和本方法的参数this做区别,表示这个name指的是Person这个类的name属性,而不是name参数,如果去掉这个this,执行完这个方法后,Person类的name属性仍然为null
getName方法返回的Person类的name,之所以不用this是因为没有必要,因为编译器会知道这个name就指的是Person的name而不是其他的name(因为找个方法没有name变量和它混淆)。当然,这个方法你也可以显示的使用return this.name,没错。
3.定冠词the用法
定冠词的用法
定冠词the与指示代词this,that同源,有"那(这)个"的意思,但意义较弱,可以和一个名词连用,来表示某个或某些特定的人或东西。
1)特指双方都明白的人或物。例如:
Take the medicine. 把药吃了。
2)上文提到过的人或事。例如:
He bought a house. I've been to the house. 他买了幢房子。我去过那幢房子。
3)指世上独一物二的事物,如the sun, the sky, the moon, the earth等。
4)与单数名词连用表示一类事物,如the dollar 美元; the fox 狐狸;或与形容词或分词连用,表示一类人:the rich 富人; the living 生者。
5)用在序数词和形容词最高级,及形容词only,very,same等前面。例如:
Where do you live? I live on the second floor. 你住在哪?我住在二层。
That's the very thing I've been looking for. 那正是我要找的东西。
6)与复数名词连用,指整个群体。例如:
They are the teachers of this school.(指全体教师)
They are teachers of this school. (指部分教师)
7)表示所有,相当于物主代词,用在表示身体部位的名词前。例如:
She caught me by the arm.. 她抓住了我的手臂。
8)用在某些由普通名词构成的国家名称、机关团体、阶级、等专有名词前。例如:
the People's Republic of China 中华人民共和国
the United States 美国
9)用在表示乐器的名词之前。例如:
She plays the piano. 她会弹钢琴。
10) 用在姓氏的复数名词之前,表示一家人。例如:
the Greens 格林一家人 (或格林夫妇)
11) 用在惯用语中。例如:
in the day, in the morning (afternoon,evening), the day after tomorrow
the day before yesterday, the next morning,
in the sky (water,field,country)
in the dark, in the rain, in the distance,
in the middle (of), in the end,
on the whole, by the way, go to the theatre