Difference Between this and super in JavaThe 'this' and the 'super' keywords are reserved words that are used in a different context. Besides this, Java also provides this() and super() constructors that are used in the constructor context. In this section, we will discuss the differences between this and super keyword and this() and super() constructor, in Java. super keyword and super() constructorsuper KeywordA reserved keyword used to call the base class method or variable is known as a super keyword. We cannot use the super keyword as an identifier. The super keyword is not only used to refer to the base class instance but also static members too. super() ConstructorThe super() is mainly used for invoking base class member functions and constructors. Let's take an example of both the super keyword and super() to understand how they work. SuperExample1.java Output: ![]() In the main() method, we have made a statement new SuperExample1(). It calls the constructor of the SuperExample1 class. Inside the constructor, we have made statement super() which calls the constructor of its parent class, i.e., Cat. In the constructor, we have made three statements:
When the second statement executes, the flow of the program jumps to Animal class to access the value of its data members. After accessing it, the flow comes back to the Cat class constructor and prints it. After that, the last statement executes and prints the value of the variables of the current class. After execution of the last statement of the Cat class, the flow comes back to the constructor of class SuperExample1 and executes the remaining statements. After completing the execution of the SuperExample1(), the flow comes back to the main() method and executes the remaining statements. Note: In order to use the super(), we have to make sure that it should be the first statement in the constructor of a class. We can use it to refer only to the parent class constructor.this keyword and this() constructorthis keywordIt is a reserved keyword in Java that is used to refer to the current class object. It is a reference variable through which the method is called. Other uses of this keyword are:
this() ConstructorThe constructor is used to call one constructor from the other of the same class. Let's take an example of both this keyword and this() to understand how they work. ThisExample1.java Output: ![]() Difference Between this and super keywordThe following table describes the key difference between this and super:
Difference Between this() and super() Constructor
Next TopicHeap implementation in Java
|