java中"this"的用法

本文详细介绍了Java中this关键字的应用场景,包括如何使用this调用本类中的成员变量、如何通过this引用本类中的其他构造方法以及如何利用return 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.
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值