深入理解 this

文章目录

  • [1. 理解 this](#1. 理解 this)
  • [2. 为了进一步理解 this,我们再看一个案例](#2. 为了进一步理解 this,我们再看一个案例)
  • [3. this 的注意事项和使用细节](#3. this 的注意事项和使用细节)

1. 理解 this

  • 什么是 this?
    java虚拟机会给每一个对象分配 this,代表当前对象,坦白的讲,要明白 this不是件容易的事,打一个比方:小明说(我是)小明,小王说(我是)小王。(我是)就相当于 this。就好像是一个话筒,谁拿到就指向谁。
  • 使用 this解决前面变量命名问题

具体看代码:

java 复制代码
public class This01 {

    //编写一个main方法
	public static void main(String[] args){

		Dog dog1 = new Dog("xjz_2002",21);
		System.out.println("main栈中 dog1.hashCode()=" + dog1.hashCode()); //dog1.hashCode=366712642 ②
		dog1.info();

	}
}

class Dog {//类

	String name;
	int age;
	//如果我们构造器的形参,能够直接写成属性名,就更好了
	//但是出现了一个问题,根据变量的作用域原则
	//构造器的 name 是局部变量,而不是属性
	//构造器的 age 是局部变量,而不是属性
	//==> 引出 this 关键字来解决
	public Dog(String name, int age){//构造器
		//this.name 就是当前对象的属性 name
		this.name = name;
		//this.age 就是当前对象的属性 age
		this.age = age;
		System.out.println("this.hashCode=" + this.hashCode()); //this.hashCode=366712642  ①
	}

	public void info(){//成员方法,输出属性 x 信息
		System.out.println("this.hashCode=" + this.hashCode()); //this.hashCode=366712642 ③
		System.out.println(name + "\t" + age + "\t"); //④
	}
}

根据以上代码我们可以看出,他们的hashCode()指向的都是同一个内存空间。

2. 为了进一步理解 this,我们再看一个案例

java 复制代码
class Person{
	String name;
	int age;

	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}

	public void info(){
		System.out.println(this.name + "\t" + this.age + "this.hashCode=" + this.hashCode());

	}
}

附图:

3. this 的注意事项和使用细节

  1. this 关键字可以用来访问本类的属性方法构造器
  2. this 用于区分当前类的属性和局部变量
  3. 访问成员方法的语法:this.方法名(参数列表);
  4. 访问构造器语法:this(参数列表); 注意只能在构造器中使用 (即只能在构造器中访问另外一个构造器, 必须放在第一条语句)
  5. this 不能在类定义的外部使用,只能在类定义的方法中使用
相关推荐
耀耀_很无聊16 分钟前
09_Jenkins安装JDK环境
java·运维·jenkins
yunyun3212317 分钟前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
ノBye~18 分钟前
Centos7.6 Docker安装redis(带密码 + 持久化)
java·redis·docker
黑臂麒麟19 分钟前
openYuanrong:多语言运行时独立部署以库集成简化 Serverless 架构 & 拓扑感知调度:提升函数运行时性能
java·架构·serverless·openyuanrong
m0_6625779719 分钟前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
XiaoLeisj28 分钟前
Android Jetpack 页面架构实战:从 LiveData、ViewModel 到 DataBinding 的生命周期管理与数据绑定
android·java·架构·android jetpack·livedata·viewmodel·databinding
⑩-32 分钟前
为什么要用消息队列?使用场景?
java·rabbitmq
似水明俊德34 分钟前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
ℳ๓₯㎕.空城旧梦1 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
Allnadyy1 小时前
【C++项目】从零实现高并发内存池(一):核心原理与设计思路
java·开发语言·jvm