Java——this关键字用法

this是Java中常用的关键字

功能详解

1.调用类中属性(this.属性)

当局部变量和成员变量重名时,就需要用this关键字进行区分

public Student(int sid, String name) {
		this.sid = sid;//this.sid是成员属性
		this.name = name;//成员变量和局部变量重名,就需要用this来区分二者了
	}

2.调用类中的普通方法和构造方法(this.方法名()、this())

this()调用构造方法,且只能放在构造方法的第一句

public Student(String name) {
		this.name = name;
	}
	
	public Student(int sid, String name) {
		this(name);//调用的构造方法为public Student(String name)
		
		this.sid = sid;
//		this.name = name;
	}

 this.方法名;调用普通方法

public int number10() {
		return this.changeNum();
	}
	
	public int changeNum() {
		return 10;
	}

3.表示当前对象的引用


    public Student getCurrent() {
		return this;
	}

	
	public static void main(String[] args) {
		Student s = new Student(9,"tom");
		System.out.println(s.getCurrent());
		
	}

运行结果:

注意:这是重写了toString()方法后的输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值