本文介绍了“这个”之间的差异和"超级" Java中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关键字超级之间有什么区别?

What is the difference between the keywords this and super?

两者都用于访问类的构造函数吗?您能否解释一下?

Both are used to access constructors of class right? Can any of you explain?

推荐答案

让我们考虑一下这种情况

Lets consider this situation

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}

class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void anotherEat() {
    super.eat();
  }
}

public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eat();
    d.anotherEat();
  }
}

输出将是

animal : eat
dog : eat
animal : eat

第三行是打印animal:eat因为我们正在调用 super.eat()。如果我们调用 this.eat(),它将打印为dog:eat。

The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".

这篇关于“这个”之间的差异和"超级" Java中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 02:24