008 Java中this和super关键字诠释 this和super的区别

this

  • 当前对象的默认引用。
  • 可以调用对象的示例变量、实例方法、构造方法(调用构造方法时必须在重载方法内部,且必须是第一行)。
  • 不能调用类变量和类方法(即static修饰的方法和变量),也不能调用局部变量。

this指向当前对象

public class Apple {

    int a;
    Apple eatApple(){
        a++;
        return this;
    }

    public static void main(String[] args) {
        Apple apple = new Apple();
        apple.eatApple().eatApple().eatApple();
    }
}

this.xxx属性,表示当前类的属性

区别类中的num和参数num;

public class Apple {
    private int num;
    
    public Apple(int num){
        this.num = num;
    }
}

this 作用于构造函数

public class Apple {

    private int num;
    private String color;

    public Apple(int num){
    	//this 必须在第一行,否则不能编译通过
        this(num,"red");
    }

    public Apple(String color){
        this(1,color);
    }
    public Apple(int num,String color){
        this.num = num;
        this.color = color;
    }

}

this 必须在第一行,否则不能编译通过
在这里插入图片描述

super

  • 代表对象的直接父类的默认引用
public class Apple extends Fruit{

    @Override
    public void eat() {
        super.num = 5;
        System.out.println("eat apple");
    }
}


class Fruit{
    public int num;
    private String color;
    public void eat(){
        System.out.println("eat fruit");
    }
}

下面示例报错的原因:父类color属性是私有的
在这里插入图片描述
修改后就不报错了
在这里插入图片描述

this super区别

关键字thissuper
调用方式本类的属性、构造函数、实例方法父类的属性、构造函数、实例方法
调用位置构造函数调用,必须第一行;其他无要求构造函数调用,必须第一行;其他无要求
调用次数一个构造函数调用一次一个构造函数调用一次

super、this 出现在方法中注意事项

  • super 代表当前对象直接父类对象的默认引用
  • this 代表当前对象的默认引用
  • super、this 出现在构造方法中,只能是构造方法的第一行,且不能同时出现
  • 在类方法(即static修饰的方法)中不允许出现this、super关键字
  • 在实例方法中 this super 不要求是第一行,且可以共存。
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值