1.this
this关键字在java中有多种使用方法,其中以下三种是常用的方法。
①:调用 成员属性:
语法: this.成员属性 ------更好的区分 重名的局部变量
例如:
程序语句赋值时,是将右边的值赋给左边,而在上图的函数中,效果实际相当于形参name = 形参name,而实际上并没有达到我们想要的形参给实参赋值名字的结果。这时我们就需要在左边name前面加上this关键字,这样就可以很好的区分成员属性和局部变量了。
②:调用 成员函数
语法 this.成员函数
public static void insertionSortTest() {
int[] tempUnsortedKeys = { -100, 5, 3, 6, 10, 7, 1, 9 };
String[] tempContents = { "null", "if", "then", "else", "switch", "case", "for", "while" };
DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
System.out.println(tempDataArray);
tempDataArray.hs();
System.out.println("Result\r\n" + tempDataArray);
}// Of insertionSortTest
void hs() {
this.insertionSort();
}//Of hs
例如tempDataArray.hs(); 进入到DataArray类中,jvm加载的类就是DataArray类,而this指代的就是DataArray类当前的一个对象,也就是例子中的tempDataArray.
③:调用 构造函数
语法:this() 代表调用本类的其他构造函数
要求:必须要本类的构造函数的第一句使用。
public graph1(int paraNumNodes) {
connectivityMatrix = new IntMatrix(paraNumNodes, paraNumNodes);
}//Of the first constructor
/**
*
* @param paraMatrix the number of nodes in the graph
*/
public graph1(int [][] paraMatrix) {
this(paraMatrix.length);
connectivityMatrix = new IntMatrix(paraMatrix);
}// Of the second constructor
如果没扔第一排,则会出现一下报错,并且不能写两个,因为写两个的话都会争着第一,从而出现错误。
所以说,为什么一定要放在第一排?