java 关于this和super

什么是this

代表指向当前类的一个引用,比如当前类是A,那么this就指代指向类A的引用。

什么是super

是一个关键字,可以指导编译器调用父类的相关的可访问资源(非private).。

特别注意!!

super并不指向父类的引用,他只是一个关键字,让你操控父类的相关资源而已,而this则指我这个类实实在在的引用,我们可以从java核心技术第一卷中的chapter5看到这句话

Some people think of super as being analogous to the this reference.
However, that analogy is not quite accurate: super is not a reference to an
object. For example, you cannot assign the value super to another object
variable. Instead, super is a special keyword that directs the compiler to
invoke the superclass method.

大概意思就是说,super不是一个对象的引用,你不能把他赋值给另一个对象变量,这是和this不一样的,我们可以写代码看看:

public class F extends SimpleDateFormat {

    public void m1(){
       F f = this; // 这么做是允许的
       F g = super; // 这是不允许的,编译器会报错
    }
    public static void main(String[] args) throws IOException {

    }
}

关于用法

用法的话相信大家都很清楚的,

  • 用于调用构造方法
class P{
    public P(){
        System.out.println("P constructor invoke");
    }
}

class C extends P{
    public C(){
        // 无参调用有参
        // this("test");
        // 调用父类构造
        super();// 这句其实也是隐式存在的,即便你不写。
        System.out.println("C constuctor invoke");
    }

    public C(String s){
        System.out.println("C parameter constructor invoke");
    }
}
  • 用于调用成员方法
class P{

    public void m1(){
        System.out.println("p m1");
    }
}

class C extends P{

    public void m1(){
        // 这是调用的父类的m1方法
        super.m1();
    }

}
  • 用于调用成员变量(比如局部变量和成员变量名称冲突的时候)
class P{

    String v1;

    public void setV1(String v1) {
        this.v1 = v1;
    }

    public P(){
        System.out.println("P constructor invoke");
    }
}

class C extends P{

    String v1;

    public void setV1(String v1) {
        // 此处是局部变量v1赋值给此类中的v1
        this.v1 = v1;
        // 下面是父类中的v1赋值给此类中的v1
        this.v1 = super.v1;
    }

    public C(){
        // 无参调用有参
        this("test");
        System.out.println("C constuctor invoke");
    }

    public C(String s){
        System.out.println("C parameter constructor invoke");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值