面向对象之this关键字

this关键字
this关键字的引入 当局部变量和成员变量重名的时候,可以考虑使用this来区分

this代表当前对象,详细原理看内存图如下
在这里插入图片描述
this的特点:
1.成员变量和局部变量重名的时候使用this
2.创建任何一个对象都会创建一个this引用和对象指向同一个堆区的空间
3.this代表当前对象,谁调用了this就是指得谁
4.this只能够出现在类的内部
5.this的设计代表现实生活中代词的概念 (“我的”)
6.默认访问类的成员都可以使用this来访问,如果访问成员没有书写this,默认系统会加上this

代码实现如下

/*
 * 代码演示封装一个苹果手机类
 */
public class PrivateDemo02 {
	public static void main(String[] args) {
		// OOP: 在主方法中,尽量不要出现逻辑计算代码,最好是不断地创建对象,使用对象
//		AppleMobile mobile = new AppleMobile();
//		mobile.setBrand("苹果7 plus");
//		mobile.setColor("中国红");
//		mobile.setPrice(7800.0);
//		
//		String brand = mobile.getBrand();
//		String color = mobile.getColor();
//		double price = mobile.getPrice();
//
//		System.out.format("手机的品牌是: %s,手机的颜色是%s,手机的价格是%f", 
//				brand, color, price);
//
//		AppleMobile mobile2 = new AppleMobile();
//		mobile2.setBrand("苹果8");
//		mobile2.setColor("白色");
//		mobile2.setPrice(9000.0);
		
		AppleMobile mobile = new AppleMobile();
//		mobile.test(new AppleMobile());
		mobile.setBrand("hello");
		mobile.show();
		
		AppleMobile mobile2 = new AppleMobile();
		mobile2.setBrand("world");
		mobile2.show();
	}
}

class AppleMobile {
	private String brand;
	private String color;
	private double price;

	public void call() {
		System.out.println("AppleMobile.call()");
	}

	public String getBrand() {
		return this.brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getColor() {
		getPrice();
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	//				AppleMobile mobile = this;
	public void test(AppleMobile mobile) {
		System.out.println(mobile.brand);
	}
	
	public void show() {
		this.test(this);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值