java中"this"的用法
注意:this关键字必须放在非静态方法中,也就是this不能出现在static方法中
1,this调用本类中的成员变量;
public class Student
{
String name; //定义一个成员变量
private void SetName(String name)//定义一个参数(局部变量)name
{
this.name = name;//将局部变量的值传递给成员变量
}
}
2,this引用本类中其他构造方法,且调用时要放在构造方法的首行。
public class Student
{
public Student(String name){}//定义一个带形参的构造方法
public Student() //定义一个无参的构造方法
{
this("hello!")
}
}
public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 1, 1); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... }
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1x1 Rectangle
at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.
3,返回当前对象的引用(return this)
public ThisTest increment()
{
this.i++;
return this;//返回的是当前对象的引用,该对象属于ThisTest.
}
上一篇: 粽子和茶可以一起吃吗,是否有助于消化吗
下一篇: 芹菜如何炒之芹菜炒肉的制作方法