每日学习-Java基础(九)类和对象5(this)

一、this

public class Hero {
	String name; // 英雄名称
	float hp; // 血量
	float armor; // 护甲
	int moveSpeed; // 移动速度

	// this
	// this 代表当前对象
	// 打印内存中的虚拟地址
	// this 当前对象
	Hero() {
		System.out.println("this 当前对象的地址:" + this);
	}

	public static void main(String[] args) {
		Hero garen = new Hero();
		System.out.println("garen 创建对象的地址:" + garen);
	}
}

运行结果:打印的地址相同,this代表当前对象
在这里插入图片描述
二、this访问属性、构造方法

public class Hero {
	String name; // 英雄名称
	float hp; // 血量
	float armor; // 护甲
	int moveSpeed; // 移动速度
/*
	Hero(String name, float hHp) {
		name = name; // name 都是参数name,因为参数name和属性name名称相同,只能访问参数name,不能访问属性name
		hp = hp;
	}

	Hero(String hName, float hHp) {
		name = hName; // name是属性name,要想访问属性name,参数名称、属性名称需不同,这样不直观
		hp = hHp;
	}
*/
	// this 访问当前对象属性  this.属性名称
	// this 访问构造方法         this(0个或多个参数)
	Hero() {
		System.out.println("this当前对象的地址:" + this);
	}
	
	Hero(String name) {
		this(); // 必须放在第一行   访问无参的构造方法
		this.name = name; // this.name表示当前对象的属性,name即参数name,不再怕同名
	}

	Hero(String name, float hp) {
		this(name); // 必须放在第一行  访问带1个参数的构造方法
		this.hp = hp; // this.hp表示当前对象的属性,hp是参数hp
	}

	Hero(String name, float hp, float armor, int moveSpeed) {
		this(name, hp); // 访问带2个参数的构造方法
		this.armor = armor;
		this.moveSpeed = moveSpeed;
	}

	public static void main(String[] args) {
		Hero teemo = new Hero("teemo");
		System.out.println("teemo的地址:" + teemo);
		System.out.println(teemo.name);

		Hero dead = new Hero("dead", 100.0f);
		System.out.println("dead的地址:" + dead);
		System.out.println(dead.name + " " + dead.hp);

		Hero hunter = new Hero("hunter", 200.0f, 20.0f, 90);
		System.out.println("hunter的地址:" + hunter);
		System.out.println(hunter.name + " " + hunter.hp + " " + hunter.armor
				+ " " + hunter.moveSpeed);
	}
}

运行结果:
在这里插入图片描述
我的学习源泉:https://how2j.cn/k/class-object/class-object-this/294.html?p=114999
Java自学网站:https://how2j.cn?p=114999

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值