一、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