讲谈Java - this和super的区别

Java中this 和super都是Java中的关键字,那他们有什么区别呢?


一、this


this 表示的当前对象,this 可以调用方法、调用属性和指向对象本身。

this 在 Java 中的使用一般有三种:

1、指向当前对象

public class Apple {
  int i = 0;

  Apple eatApple(){
    i++;
    return this;
  }

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

}

这段代码比较精妙,精妙在哪呢,我一个eatApple()方法竟然可以调用多次,你在后面还可以继续调用,这就很神奇了,为啥呢?其实就是 this 在作祟了,我在eatApple方法中加了一个return this的返回值,也就是说哪个对象调用eatApple方法都能返回对象的自身。

2、this还可以修饰属性,最常见的就是在构造方法中使用this ,如下所示

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

  public static void main(String[] args) {
    new Apple(10);
  }
}

main方法中传递了一个int值为10的参数,它表示的就是苹果的数量,并把这个数量赋给了num 全局变量。所以num的值现在就是10。


3、this 还可以和构造函数一起使用,充当一个全局关键字的效果
 

public class Apple {
  private int num;

  private String color;

  public Apple(int num){
    this(num,"红色");
  }
 
  public Apple(String color){
   this(1,color);
  }

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

你会发现上面这段代码使用的不是 this,而是 this(参数)。它相当于调用了其他构造方法,然后传递参数进去。这里注意一点: this()必须放在构造方法的第一行,否则编译不通过

二、super

如果你把 this 理解为指向自身的一个引用,那么super就是指向父类的一个引用。super关键字和this一样,你可以使用 super .对象 来引用父类的成员,如下

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

public class Apple extends Fruit{
  @Override
  public void eat() {
    super.num = 10;
    System.out.println("eat " + num + " Apple");
  }
}

你也可以使用super(参数)来调用父类的构造函数。

总结:

关键字thissuper
调用方式调用本类中的属性、构造函数、方法调用父类中属性、构造函数、方法
调用位置构造函数第一行,其他可自行指定构造函数第一行,其他可自行指定
调用次数—个构造函数只能调用一次—个构造函数只能调用一次


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值