What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
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 keyword
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.
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.This almost appears to be a situation where a person has asked a question that everyone sees only one possible answer for. Yet the person calls each answer a non-answer, so everyone tries a different variant on the same answer since there appears to be only one way to answer it.
So, one person starts out with A is a class and B is its subclass. The next person starts out with C is a Class and B is its subclass. A third person answers it a little differently. A is a class and B extends A. Then a fourth one says A is A class that gets extended as B is defined. Or Animal is a class and Dog is a subclass. Or Nation is a class and China is a special case of Nation.
Or better yet, Man is a class, and Clark Kent is a subclass of Man. So, Superman...no...that doesn't work in terms of Java....
Well, it's at least another attempt to come up with a different description that nobody came up with that might explain things differently. Arggghhhh.
It seems to me that everyone's explanation worked except mine.
this
is a reference to the object typed as the current class, andsuper
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 wheresuper.method()
will call the same method as defined in the parent class.