JAVA --类与对象(五)this


this

this这个关键字,相当于普通话里的“我”
this即代表当前对象

package 学习;

public class adhero extends hero{
	public void method() {
		System.out.println("打印this看到的虚拟地址:	" + this);
	}
	public static void main(String args[]) {
		adhero a  = new adhero();
		System.out.println("打印对象获取的虚拟地址:	" + a );
		a.method();
	}
}

结果为:
打印对象获取的虚拟地址: 学习.adhero@54bedef2
打印对象看到的虚拟地址: 学习.adhero@54bedef2

通过this 访问属性

public class hello {
	String name;
	public void method(String name) {
		this.name = name;
		System.out.println(name);
	}
	public static void main(String args[]) {
		hello a = new hello();
		a.method("二狗子");
	}
}

通过this调用其他的构造方法

public class hello {
	String name;
	int hp;
	public hello(String name) {
		this.name = name;
		System.out.println(name);
	}
	public hello(String name,int hp) {
		this(name);
		this.hp = hp;
		System.out.println(name + hp);
	}
	public static void main(String args[]) {
		hello a = new hello("皮皮呀");

		hello b = new hello("赛丽亚",200);

	}
}

综合练习:参考练习-构造方法 设计一个构造方法,但是参数名称不太一样,分别是
String name
float hp
float armor
int moveSpeed

不仅如此,在这个构造方法中,调用这个构造方法

public class hello {
	String name;
	float hp;
	int movespeed;
	float armor;
	public hello(String name,int movespeed,float hp,float armor) {
		this.name = name;
		this.hp = hp;
		this.movespeed = movespeed;
		this.armor = armor;
		System.out.println("姓名为:" + name);
		System.out.println("生命值为:" + hp);
		System.out.println("移动速度为:" + movespeed);
		System.out.println("护甲值为:" + armor);
	}	
	public static void main(String args[]) {
		hello a = new hello("无极剑圣",150,500,20);
	}
}

在这里插入图片描述