打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java中this的用法

一、this关键字

1.this的类型:哪个对象调用就是哪个对象的引用类型

二、用法总结

1.this.data; //访问属性

2.this.func(); //访问方法

3.this(); //调用本类中其他构造方法

三、解释用法

1.this.data

这种是在成员方法中使用

让我们来看看不加this会出现什么样的状况

  1. class MyDate{
  2. public int year;
  3. public int month;
  4. public int day;
  5. public void setDate(int year, int month,int day){
  6. year = year;//这里没有加this
  7. month = month;//这里没有加this
  8. day = day;//这里没有加this
  9. }
  10. public void PrintDate(){
  11. System.out.println(year+"年 "+month+"月 "+day+"日 ");
  12. }
  13. }
  14. public class TestDemo {
  15. public static void main(String[] args) {
  16. MyDate myDate = new MyDate();
  17. myDate.setDate(2000,9,25);
  18. myDate.PrintDate();
  19. MyDate myDate1 = new MyDate();
  20. myDate1.setDate(2002,7,14);
  21. myDate1.PrintDate();
  22. }
  23. }

我们想要达到的预期是分别输出2000年9月25日,2002年7月14日。

而实际输出的结果是

而当我们加上this时

  1. class MyDate{
  2. public int year;
  3. public int month;
  4. public int day;
  5. public void setDate(int year, int month,int day){
  6. this.year = year;
  7. this.month = month;
  8. this.day = day;
  9. }
  10. public void PrintDate(){
  11. System.out.println(this.year+"年 "+this.month+"月 "+this.day+"日 ");
  12. }
  13. }
  14. public class TestDemo {
  15. public static void main(String[] args) {
  16. MyDate myDate = new MyDate();
  17. myDate.setDate(2000,9,25);
  18. myDate.PrintDate();
  19. MyDate myDate1 = new MyDate();
  20. myDate1.setDate(2002,7,14);
  21. myDate1.PrintDate();
  22. }
  23. }

 就实现了赋值的功能,为了避免出现差错,我们建议尽量带上this

2.this.func()

这种是指在普通成员方法中使用this调用另一个成员方法

  1. class Student{
  2. public String name;
  3. public void doClass(){
  4. System.out.println(name+"上课");
  5. this.doHomeWork();
  6. }
  7. public void doHomeWork(){
  8. System.out.println(name+"正在写作业");
  9. }
  10. }
  11. public class TestDemo2 {
  12. public static void main(String[] args) {
  13. Student student = new Student();
  14. student.name = "小明";
  15. student.doClass();
  16. }
  17. }

运行结果:

 (3)this()

这种指在构造方法中使用this调用本类其他的构造方法

这种this的使用注意以下几点

1.this只能在构造方法中调用其他构造方法

2.this要放在第一行

3.一个构造方法中只能调用一个构造方法

运行结果

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java学习——33、浅拷贝和深拷贝
java 计算时间段
求!!关于用java判断输入3个数组成什么三角形
java Date获取 年月日时分秒
JAVA的安装
从零开始学Java(十三)Java中this关键字的使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服