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);
}
}