发布于2022-06-15 22:02 阅读(446) 评论(0) 点赞(0) 收藏(0)
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.一个构造方法中只能调用一个构造方法
运行结果
原文链接:https://blog.csdn.net/benxiangsj/article/details/124282800
作者:飞人出击
链接:http://www.javaheidong.com/blog/article/456727/f7e3152320bc53785933/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!