Java this关键字(调用属性,调用方法,调用当前对象)

·调用属性(代码示例):

public class thisDemo01 {
	public static void main(String[] args) throws Exception {
		BlueMoon bm=new BlueMoon("渣渣辉", 100);
		System.out.println(bm.getInfo());
	}
}

class BlueMoon {
	private String name;
	private int level;

	public BlueMoon(String name, int level) {
		this.name = name;
		this.level = level;
	}

	public String getInfo() {
		return "大家好!我是" + this.name + ",我是贪玩蓝月的战士,等级:" + this.level;
	}
}

·调用方法(普通方法与构造方法)

 |—调用普通方法:

public class thisDemo01 {
	public static void main(String[] args) throws Exception {
		BlueMoon bm = new BlueMoon("渣渣辉", 100);
		System.out.println(bm.getInfo());
	}
}

class BlueMoon {
	private String name;
	private int level;

	public BlueMoon(String name, int level) {
		this.name = name;
		this.level = level;
	}

	public void print() {
		System.out.println("************************");
	}

	public String getInfo() {
		this.print();//调用普通方法
		return "大家好!我是" + this.name + ",我是贪玩蓝月的战士,等级:" + this.level;
	}
}
 |—调用构造方法:

public class thisDemo01 {
	public static void main(String[] args) throws Exception {
		BlueMoon bm1 = new BlueMoon();
		BlueMoon bm2 = new BlueMoon("古天乐");
		BlueMoon bm3 = new BlueMoon("小志传奇", "陈赫", "法师");

		System.out.println(bm1.getInfo());
		System.out.println(bm2.getInfo());
		System.out.println(bm3.getInfo());
	}
}

class BlueMoon {
	private String game;
	private String name;
	private String title;
	private int level;

	public BlueMoon() {
		this("贪玩蓝月", "无名氏", "未定", 0);
	}

	public BlueMoon(String name) {
		this("贪玩蓝月", name, "剑士", 90);
	}

	public BlueMoon(String game, String name) {
		this(game, name, "战士", 100);
	}

	public BlueMoon(String game, String name, String title) {
		this();
		this.game = game;
		this.name = name;
		this.title = title;
	}

	public BlueMoon(String game, String name, String title, int level) {
		this.game = game;
		this.name = name;
		this.title = title;
		this.level = level;
	}

	public String getInfo() {
		return "欢迎来到" + this.game + "!我是" + this.name + ",职业:" + this.title + ",等级:" + this.level + "级";
	}
}


·当前对象调用:

class BlueMoon {
	public void print() {
		//哪个对象调用了print()方法,this就自动与此对象指向同一块内存地址
		System.out.println("this=" + this);//this 就是当前调用对象
	}
}

public class thisDemo02 {
	public static void main(String[] args) throws Exception {
		BlueMoon bm = new BlueMoon();
		BlueMoon bm2 = new BlueMoon();
		System.out.println("bm=" + bm);
		bm.print();
		System.out.println("---------------------");
		System.out.println("bm2=" + bm2);
		bm.print();

	}
}





  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值