Difference between “this” and“super” keywords in Java

前端 未结 9 1779
你的背包
你的背包 2020-11-27 03:00

What is the difference between the keywords this and super?

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

相关标签:
9条回答
  • 2020-11-27 03:39

    this is a reference to the object typed as the current class, and super is a reference to the object typed as its parent class.

    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.

    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.

    0 讨论(0)
  • 2020-11-27 03:40

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

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

    0 讨论(0)
  • 2020-11-27 03:43

    this refers to a reference of the current class.
    super refers to the parent of the current class (which called the super keyword).

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

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

    0 讨论(0)
提交回复
热议问题