Java基础整理(八)

this关键字

  • this是什么?在内存中如何存储?

    this是一个变量,是一个引用。 this保存当前对象的内存地址,指向自身。this存储在堆内存当中对象的内部。严格意义上说,this代表的就是当前对象

  • this只能使用在实例方法或构造方法中。谁调用这个实例方法,this就是谁

  • 为什么this不能使用在静态方法中?

    this代表当前对象,静态方法不存在当前对象

  • "this."大部分情况下可以省略

    public class Demo {
    
        public static void main(String[] args){
            Book b1=new Book();
            b1.detail();
            Book b2=new Book();
            b2.detail();
        }
    }
    
    class Book {
    
        String title;
        int pageNum;
    
    
        public void detail(){
            System.out.println(this.title+" "+this.pageNum); //此时this可以省略 当b1调用时,this就是b1
                                                                  // 当b2调用时, this就是b2
        }
    }
    
  • this在什么情况下不能省略?

    在实例方法或构造方法中,为了区分局部变量和实例变量,不能省略。

    class Date {
    
        private int year;
        private int month;
        private int day;
    
        public Date(int year,int month, int day){
            this.year=year; //不能省略 就近原则 如果省略 两个year都是形参列表内的year
            this.month=month;
            this.day=day;
        }
    
        public int getYear(){
            return year;
        }
    
        public void setYear(int year){
            this.year=year; //不能省略
        }
    }
    
  • 可以通过this在当前的构造方法1中去调用本类中的另一个构造方法2,此时this()的作用是代码复用,语法格式:

    this(实际参数列表);
    

    注:此语法只能出现在构造方法的第一行!并且两个构造方法在一个类中

    示例:

    class Date {
    
        private int year;
        private int month;
        private int day;
    
        public Date(){
            this(1970,1,1);  //只能在第一行  
            
            /*year=1970;     两种表达方式 相同
            month=1;
            day=1;*/
        }
    
        public Date(int year,int month, int day){
            this.year=year;
            this.month=month;
            this.day=day;
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值