Java中this关键字的用法详解
一、this关键字
1.this的类型:哪个对象调用就是哪个对象的引用类型

二、用法总结
1.this.data; //访问属性
2.this.func(); //访问方法
3.this(); //调用本类中其他构造方法
三、解释用法
1.this.data
这种是在成员方法中使用
让我们来看看不加this会出现什么样的状况
class MyDate{
public int year;
public int month;
public int day;
public void setDate(int year, int month,int day){
year = year;//这里没有加this
month = month;//这里没有加this
day = day;//这里没有加this
}
public void PrintDate(){
System.out.println(year+"年 "+month+"月 "+day+"日 ");
}
}
public class TestDemo {
public static void main(String[] args) {
MyDate myDate = new MyDate();
myDate.setDate(2000,9,25);
myDate.PrintDate();
MyDate myDate1 = new MyDate();
myDate1.setDate(2002,7,14);
myDate1.PrintDate();
}
}我们想要达到的预期是分别输出2000年9月25日,2002年7月14日。
而实际输出的结果是

而当我们加上this时
class MyDate{
public int year;
public int month;
public int day;
public void setDate(int year, int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public void PrintDate(){
System.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 ");
}
}
public class TestDemo {
public static void main(String[] args) {
MyDate myDate = new MyDate();
myDate.setDate(2000,9,25);
myDate.PrintDate();
MyDate myDate1 = new MyDate();
myDate1.setDate(2002,7,14);
myDate1.PrintDate();
}
}
就实现了赋值的功能,为了避免出现差错,我们建议尽量带上this
2.this.func()
这种是指在普通成员方法中使用this调用另一个成员方法
class Student{
public String name;
public void doClass(){
System.out.println(name+"上课");
this.doHomeWork();
}
public void doHomeWork(){
System.out.println(name+"正在写作业");
}
}
public class TestDemo2 {
public static void main(String[] args) {
Student student = new Student();
student.name = "小明";
student.doClass();
}
}运行结果:

3.this()
这种指在构造方法中使用this调用本类其他的构造方法
这种this的使用注意以下几点
1.this只能在构造方法中调用其他构造方法
2.this要放在第一行
3.一个构造方法中只能调用一个构造方法


运行结果

总结
到此这篇关于Java中this关键字用法的文章就介绍到这了,更多相关Java this关键字用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
JDK14的新特性NullPointerExceptions的使用
这篇文章主要介绍了JDK14的新特性NullPointerExceptions的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-04-04
Java项目中Service 层不直接返回Result 对象的原因分析
在Service层直接返回Result对象会导致业务逻辑与表现逻辑耦合,降低代码清晰度和可维护性,正确的做法是让每一层专注于自己的职责,保持代码可复用性,这篇文章给大家介绍为什么Java里面,Service 层不直接返回Result对象,感兴趣的朋友跟随小编一起看看吧2026-02-02
Java基础之重载(Overload)与重写(Override)详解
这篇文章主要介绍了Java基础之重载(Overload)与重写(Override)详解,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有非常好的帮助,需要的朋友可以参考下2021-04-04
SpringBoot 整合 Lettuce Redis的实现方法
这篇文章主要介绍了SpringBoot 整合 Lettuce Redis的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-07-07
Java中使用Preferences 的 API设置用户偏好
这篇文章主要介绍了Java中使用Preferences 的 API设置用户偏好的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下2016-09-09
ShardingSphere数据库读写分离算法及测试示例详解
这篇文章主要为大家介绍了ShardingSphere数据库读写分离算法及测试示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-03-03


最新评论