欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java中"this"的用法

程序员文章站 2022-06-30 11:33:24
...

注意: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.
	}