Difference between "this" and"super" keywords in Java

Sum*_*hra 49 java keyword

What is the difference between the keywords this and super?

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

Nit*_*dra 71

让我们考虑一下这种情况

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

输出将是

animal : eat
dog : eat
animal : eat
Run Code Online (Sandbox Code Playgroud)

第三行是打印"动物:吃",因为我们正在打电话super.eat().如果我们打电话this.eat(),它会打印成"狗:吃".

  • 虽然您可以将输出的最后一行设为粗体或添加尾随注释以强调使用基类,但我发现这个答案并不令人困惑. (2认同)

Jay*_*ker 52

super用于访问基类的方法,同时this用于访问当前类的方法.

扩展这个概念,如果你写super(),它指的是基类的构造函数,如果你写this(),它引用你正在编写这段代码的类的构造函数.


Eri*_*son 19

this是对作为当前类输入的对象的引用,并且super是对作为其父类键入的对象的引用.

在构造函数中,this()调用当前类中定义的构造函数. super()调用父类中定义的构造函数.构造函数可以在任何父类中定义,但它将引用最接近当前类的重写.以这种方式调用其他构造函数可能只能作为构造函数中的第一行.

调用方法的工作方式相同.调用this.method()调用当前类中定义的方法,该方法super.method()将调用父类中定义的相同方法.


Ste*_*n C 10

从你的问题来看,我认为你真的在询问构造函数链的使用thissuper构造函数; 例如

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

区别很简单:

  • this形式链在当前类中的构造; 即在A课堂上.

  • super表格链的直接超类构造函数; 即在B课堂上.


Buh*_*ndi 8

this当前类的引用.
super指当前类的级(称为super关键字).

通过这样做this,它允许您访问当前类的方法/属性(包括其自己的私有方法/属性).

super允许您访问父(基)类的公共/受保护方法/属性.您无法看到父级的私有方法/属性.

  • 如果您将'class'的每次出现都更改为'object',那么这是正确的答案.例如,不可能从类中的静态方法调用'this'. (2认同)

Var*_*sta 5

super()&this()

  • super() - 调用父类构造函数.
  • this() - 调用相同的类构造函数.

注意:

  • 我们只能在构造函数中使用super()和this()而不是其他任何地方,任何尝试这样做都会导致编译时错误.

  • 我们必须保持super()或this()作为构造函数的第一行,但不能同时保持两者.

超级和这个关键字

  • super - 调用父类成员(变量和方法).
  • 这 - 调用相同的类成员(变量和方法).

注意:除静态区域(静态块或方法)外,我们可以在类中的任何位置使用它们,任何尝试这样做都会导致编译时错误.