Java中“this”和“super”关键字的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4023344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:36:27  来源:igfitidea点击:

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

javakeyword

提问by Sumithra

What is the difference between the keywords thisand super?

关键字this和之间有什么区别super

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

两者都用于访问类的构造函数,对吗?大家能解释一下吗?

采纳答案by Nithesh Chandra

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();
  }
}

The output is going to be

输出将是

animal : eat
dog : eat
animal : 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".

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

回答by Jaywalker

superis used to access methods of the base class while thisis used to access methods of the current class.

super用于访问基类的方法,而this用于访问当前类的方法。

Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.

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

回答by Buhake Sindi

thisrefers to a reference of the currentclass.
superrefers to the parentof the current class (which called the superkeyword).

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

By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).

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

superallows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.

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

回答by David Rabinowitz

thisis used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.

this用于访问当前对象的方法和字段。因此,例如,它在静态方法中没有意义。

superallows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.

super允许访问超类中的非私有方法和字段,并且只能从类的构造函数中访问构造函数。

回答by Erick Robertson

thisis a reference to the object typed as the current class, and superis a reference to the object typed as its parent class.

this是对类型化为当前类super的对象的引用,并且是对类型化为其父类的对象的引用。

In the constructor, this()calls a constructor defined in the current class. super()calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.

在构造函数中,this()调用在当前类中定义的构造函数。 super()调用父类中定义的构造函数。构造函数可以在任何父类中定义,但它会引用最接近当前类的被覆盖的类。以这种方式调用其他构造函数只能在构造函数的第一行进行。

Calling methods works the same way. Calling this.method()calls a method defined in the current class where super.method()will call the same method as defined in the parent class.

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

回答by Stephen C

From your question, I take it that you are really asking about the use of thisand superin constructor chaining; e.g.

从您的问题来看,我认为您确实是在询问构造函数链接中的this和的使用super;例如

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}

versus

相对

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}

The difference is simple:

区别很简单:

  • The thisform chains to a constructor in the current class; i.e. in the Aclass.

  • The superform chains to a constructor in the immediate superclass; i.e. in the Bclass.

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

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

回答by BigMac66

When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

在编写代码时,您通常不想重复自己。如果你有一个可以用不同数量的参数构造的类,一个避免重复自己的常见解决方案是简单地调用另一个在缺少参数中具有默认值的构造函数。对此只有一个恼人的限制——它必须是声明的构造函数的第一行。例子:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super()constructor, again unlike super.method()access it must be the first line of your constructor. After that it is very much like the this()constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

至于super()构造函数,再次与super.method()访问不同,它必须是构造函数的第一行。之后它非常像this()构造函数,DRY(不要重复你自己),如果你扩展的类有一个构造函数可以做一些你想做的事情,然后使用它,然后继续构造你的对象,例如:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

附加信息:

Even though you don't see it, the default no argument constructor always calls super()first. Example:

即使你没有看到它,默认的无参数构造函数总是super()首先调用。例子:

MyClass()
{
}

is equivalent to

相当于

MyClass()
{
   super();
}

I see that many have mentioned using the thisand superkeywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.

我看到很多人都提到在方法和变量上使用thissuper关键字 - 一切都很好。请记住,构造函数对其使用有独特的限制,最值得注意的是它们必须是声明的构造函数的第一条指令,并且您只能使用一条。

回答by rocketmanu

thiskeyword use to call constructor in the same class (other overloaded constructor)

this关键字用于调用同一个类中的构造函数(其他重载的构造函数)

syntax: this(args list); //compatible with args listin other constructor in the same class

语法this(参数列表);//与同一个类中其他构造函数中的args列表兼容

superkeyword use to call constructor in the super class.

super关键字用于调用超类中的构造函数。

syntax:super (args list); //compatible with args listin the constructor of the super class.

语法:超级(参数列表);//与超类构造函数中的args列表兼容。

Ex:

前任:

public class Rect {
int x1, y1, x2, y2;

public Rect(int x1, int y1, int x2, int y2) // 1st constructor 
{ ....//code to build a rectangle }
}

public Rect () {   // 2nd constructor
this (0,0,width,height) // call 1st constructor (because it has **4 int args**), this is another way to build a rectangle 
}


public class DrawableRect extends Rect {

public DrawableRect (int a1, int b1, int a2, int b2) {
super (a1,b1,a2,b2) // call super class constructor (Rect class) 
}
}

回答by Varun Vashista

super() & this()

超级() & this()

  • super() - to call parent class constructor.
  • this() - to call same class constructor.
  • super() - 调用父类构造函数。
  • this() - 调用相同的类构造函数。

NOTE:

笔记:

  • We can use super() and this() only in constructor not anywhere else, any attempt to do so will lead to compile-time error.

  • We have to keep either super() or this() as the first line of the constructor but NOT both simultaneously.

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

  • 我们必须将 super() 或 this() 作为构造函数的第一行,但不能同时保留。

super & this keyword

super & this 关键字

  • super - to call parent class members(variables and methods).
  • this - to call same class members(variables and methods).
  • super - 调用父类成员(变量和方法)。
  • this - 调用相同的类成员(变量和方法)。

NOTE:We can use both of them anywhere in a class except static areas(static block or method), any attempt to do so will lead to compile-time error.

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