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

前端 未结 9 1821
你的背包
你的背包 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条回答
  •  -上瘾入骨i
    2020-11-27 03:20

    super() & this()

    • super() - to call parent class constructor.
    • this() - to call same class constructor.

    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 keyword

    • super - to call parent class members(variables and methods).
    • this - to call same class members(variables and methods).

    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.

提交回复
热议问题