java—this用法
th
1.引用成员变量表示对当前 变量的引用
public class Students{
String name;//成员变量
private void Setname (String name){
// name= name;
this.name = name;
}
在上例子中可以看出,形式参数和成员变量都是name,把形式参数赋给成员变量,是存在二义性,虽然,你可以将他们区分开来但是计算机并不知道,所用要用到this关键字将他们区分,告诉计算机this.student 是student类的成员变量,是的计算机按照与其进行工作,当然,如果不存在二义性,最好也带上this,易于区分成员变量,是的代码的可读性变强
2.调用类的构造函数
package com.company;
public class ex {
public static class Test {
private int i = 0;
Test(int i) {
this.i = i + 1;
System.out.println("i=" + i + " this.i=" + this.i);
}
Test(String s) {
System.out.println("String=" + s);
}
Test(int i, String s) {
this(s);//调用第二个构造函数,**this的调用必须在构造器的第一行用
this.i = i--;
System.out.println("i= " + i + " String= " + s);
}
}
public static void main(String[] args){
Test x1=new Test(10);
Test x2=new Test("ok");
Test x3=new Test(20,"ok again!");
}
}
运行结果
i=10 this.i=11
String=ok
String=ok again!
i= 19 String= ok again!
注意:只能引用一个的构造方法且必须位于开始