程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(3)

Java中this的用法

发布于2022-06-15 22:02     阅读(446)     评论(0)     点赞(0)     收藏(0)


一、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.一个构造方法中只能调用一个构造方法

运行结果

原文链接:https://blog.csdn.net/benxiangsj/article/details/124282800



所属网站分类: 技术文章 > 博客

作者:飞人出击

链接:http://www.javaheidong.com/blog/article/456727/f7e3152320bc53785933/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)