Java中 this 和 super 关键字理解

首先还是来看一下例子:

package thisExample;

public class Student {

  private String name;
  private Long id;

  public Student () {

  }

  public Student (Long id) {
    this();
    this.id = id;
  }

  public Student (Long id, String name) {
    this(id);
    this.name = name;
  }

  public void print () {
    System.out.println("A method of super class");
  }

}
package thisExample;

public class MiddleStudent extends Student {

  private String book;

  public MiddleStudent () {

  }

  public MiddleStudent (Long id, String name) {
    super(id, name);
  }

  public MiddleStudent (Long id, String name, String book) {
    this(id, name);
    this.book = book;
  }

  public void print () {
    System.out.println("Override the super class method!");
  }

  public void show () {
    this.print(); //这里为了区分比较,没有将this取消掉
    super.print();
    System.out.println("A method of sub class");
  }

}
package thisExample;

public class StudentTest {

  public static void main(String[] args) {
    MiddleStudent ms = new MiddleStudent();
    ms.show();
  }

}

// 输出结果:Override the super class method!
//          A method of super class
//          A method of sub class

1.首先看一下超类Student类中用到的this,有两种用法,一种是this()或者this(para...) ;另外一种是this.para

第一种情况只能用在构造器中,也就是一个构造器可以调用另一种构造器,但是构造器不能调用自己本身,也就是不能在构造器中形成递归;

第二种情况是调用当前类的成员变量和方法。在类中构造器或非构造器方法中都可以使用。其实个人觉得第二中情况一般都是使用this调用当前类的变量,来区分与变量同名的方法参数,当调用方法的时候,this可以直接省略掉。。。

2.接着看一下Student的子类MiddleStudent,是怎样调用this和super的。

this(para...)的用法还是不变的,这里主要比较一下this(para...)super(para...)

这里写图片描述

这里写图片描述

看上面两个图就很明显,super(para...) 调用的是父类的构造器,而this(para...) 调用的是当前对象的构造器。

我们都知道不管是super(para...) 还是this(para...) 都只能放在构造器的第一行,所以他俩不能混用,反正就是一个构造器只能调用他俩之中的一个。

super可以调用父类所有非私有的成员变量和方法,这时就不能像this调用方法那么任性可以取消的,如果想调用父类的方法,必须加上super。

写到这里大家应该都清楚这两个用法和区别了,以后遇到其他的再补充。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值