Java中this关键字的用法

1.使用this调用本类中的属性

package com.yxf.stringdemos;

public class StringDemos {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Person p1 = new Person("xifeng.yang","30");
        p1.getInfo();
	}
}

class Person{
	String name;
	String age;
	
	public Person(String name, String age){
		System.out.println("Constrctor, name = " + name + ",age = " + age);
		name = name;//这里不加this时,则调用构造方法赋值失败
		age = age;
	}
	
	public void getInfo(){
		System.out.println("name = " + name + ", age = " + age);
	}
}
结果:

Constrctor, name = xifeng.yang,age = 30
name = null, age = null

2.使用this调用构造方法

如果一个类中有多个构造方法,则可以使用this关键字相互调用。

package com.yxf.stringdemos;

public class StringDemos {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Person p1 = new Person("xifeng.yang","30");
        Person p2 = new Person("Chris Yang");
        Person p3 = new Person();
        p1.getInfo();
	}
}

    class Person{
	String name;
	String age;
	
	public Person(String name, String age){
		System.out.println("Person,constructor()");
		this.name = name;
		this.age = age;
	}
	
	public Person(String name){
		this(name,null);
	}
	
	public Person(){
		this(null,null);
	}

	public void getInfo(){
		System.out.println("name = " + name + ", age = " + age);
	}
    }
}
这里面p1,p2,p3都会调用第一个构造方法。

3.this表示当前对象

使用this可以表示当前正在调用类的方法的对象

package com.yxf.stringdemos;

public class StringDemos {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Person p1 = new Person("xifeng.yang","30");
        System.out.println("Main: " + p1);
        p1.getInfo();
        Person p2 = new Person("Chris Yang");
        System.out.println("Main: " + p2);
        p2.getInfo();
	}
}

class Person{
	String name;
	String age;
	
	public Person(String name, String age){
		this.name = name;
		this.age = age;
	}
	
	public Person(String name){
		this(name,null);
	}
	
	public Person(){
		this(null,null);
	}
	public void getInfo(){
		System.out.println("getInfo(): " + this);
	}
}
结果:

Main: com.yxf.stringdemos.Person@1fb8ee3
getInfo(): com.yxf.stringdemos.Person@1fb8ee3
Main: com.yxf.stringdemos.Person@61de33
getInfo(): com.yxf.stringdemos.Person@61de33

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值