java基础回顾第五天

第五章

  • this
  • 总结
this总结:

在这里插入图片描述

  1. 一个对象一个this

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

  3. this只能使用在实例方法中,谁调这个实例方法,this就是谁,所以this代表的是当前对象。

  4. “this.”大部分情况下是可以省略的。

  5. 什么时候不能省略?

    当实例方法传参的参数名和实例变量的参数名一样时,必须用this.name = name

  6. 为什么this不能使用到静态方法中? 因为this是当前对象,而静态方法的调用是不需要对象的参与的。

  7. this除了可以使用在实例方法中,也可以使用在构造方法中。

    新语法:通过当前的构造方法调用去另一个本类的构造方法,可以使用以下语法格式:this();

    this()必须在构造方法的第一行,否则报错

    this()作用:代码复用

    package day3;
    
    public class Date {
    
        private int year;//年
    
        private int month;//月
    
        private int day;//日
    
        public Date() {
            /*this.year = 1970;
            this.month = 1;
            this.day = 1;*/
            this(1970,1,1);//等价于上面三行代码,是在无参构造方法中调用了下面的有参构造方法。相当于在调用无参构造方法时,给实例变量赋初始默认值,这种语法更简洁。
        }
    
        public Date(int year, int month, int day) {
            this.year = year;
            this.month = month;
            this.day = day;
        }
    
        public void detail(){
            System.out.println("年:"+year+" 月:"+month+" 日:"+day);
        }
    
        public int getYear() {
            return year;
        }
    
        public void setYear(int year) {
            this.year = year;
        }
    
        public int getMonth() {
            return month;
        }
    
        public void setMonth(int month) {
            this.month = month;
        }
    
        public int getDay() {
            return day;
        }
    
        public void setDay(int day) {
            this.day = day;
        }
    
    }
    
    
静态不能直接方法访问实例变量:

在这里插入图片描述

不同类型变量存储不同

在这里插入图片描述

总结

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值