For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
As an object-oriented programming language, Java provides potent tools such as this and super keywords to improve the functionality and maintainability of source code. This article will examine the versatility of the "this" and "super" keywords in Java, as well as their crucial functions in referencing objects and calling constructors. By understanding their characteristics, distinctions, and typical applications, you will be able to leverage the full potential of these Java programming keywords.
The "this" and "super" keywords are fundamental to Java programming, enabling efficient object manipulation and class hierarchy navigation. The primary purpose of the "this" keyword is to refer to the current object, while the "super" keyword allows access to the members of the parent class. These keywords help resolve naming conflicts, differentiate between instance variables and parameters, and invoke constructors effectively.
The "this" keyword in Java refers to the current object. It provides a convenient way to access the members (variables and methods) of the current class. By using "this," you can distinguish between local variables and instance variables or parameters with the same names. Let's illustrate this with an example:
In the above example, the "this" keyword is used to differentiate between the parameter name and the instance variable name. It clarifies that we are assigning the value of the parameter to the instance variable. Similarly, in the displayName() method, "this" is used to access the instance variable and display the name.
The "this" keyword in Java serves several purposes, including:
Let's explore a few examples to demonstrate the practical usage of the "this" keyword in Java:
Example 1: Constructor Chaining
In the above example, the default constructor invokes the parameterized constructor using "this," allowing us to set the initial values of width and height using a single line of code.
Example 2: Method Parameter Shadowing
In this example, the "setRadius" method takes a parameter with the same name as the instance variable. By using "this," we explicitly indicate that we are referring to the instance variable.
Example 3: Method Chaining
In this example, the "Calculator" class demonstrates method chaining using the "this" keyword. The "add" method adds the given value to the result, and it returns the instance of the class itself using "this." This allows consecutive method calls in a fluent manner.
Example 4: Accessing Inner Class Variables
In this example, the "Outer" class contains an inner class called "Inner." Inside the "displayValues" method of the inner class, "this" is used to access the value of the inner class, while "Outer.this" is used to access the value of the outer class. Additionally, a local variable with the same name is accessed without any keywords.
The "super" keyword in Java allows access to the members (variables and methods) of the parent class. It is primarily used in inheritance scenarios, where a subclass extends a parent class. By using "super," you can invoke the parent class's constructor, access overridden methods, and refer to parent class variables.
The "super" keyword finds its utility in several scenarios:
Let's dive into a few examples to illustrate the usage of the "super" keyword in Java:
Example 1: Invoking Parent Class Constructor
In this example, the "Car" class extends the "Vehicle" class. The "super" keyword is used in the constructor of the "Car" class to invoke the parameterized constructor of the "Vehicle" class, passing the "brand" parameter.
Example 2: Accessing Parent Class Method
In this example, the "Square" class extends the "Shape" class. The overridden "getArea" method in the "Square" class uses the "super" keyword to invoke the parent class's "getArea" method, ensuring that the parent class's logic is also executed.
Example 3: Overriding a Parent Class Method
In this example, the "Vehicle" class has a method called "displayInfo." The "Car" class extends the "Vehicle" class and overrides the "displayInfo" method. Inside the overridden method, "super.displayInfo()" is used to invoke the parent class's version of the method before adding additional functionality specific to the "Car" class.
Example 4: Accessing Parent Class Variables
In this example, the "Animal" class has a variable called "species." The "Dog" class extends the "Animal" class and has its own variable called "name." Inside the "displayInfo" method, "super.species" is used to access the value of the parent class's "species" variable, while "this.name" is used to access the value of the "name" variable in the "Dog" class.
Feature | "this" Keyword | "super" Keyword |
Refers to | Current object | Parent class |
Usage | Inside the same class | Inherited classes |
Constructor Invocation | Invokes other constructors | Invokes parent class constructor |
Variable Access | Accesses current class variables | Accesses parent class variables |
Method Invocation | Invokes current class methods | Invokes parent class methods |
While the "this" and "super" keywords have distinct functionalities, they also share some similarities:
Yes, Java permits both "this()" and "super()" to be used in the same constructor. However, specific principles must be followed:
Here are some essential points to consider when using the "this()" and "super()" keywords in Java:
Whenever a derived class inherits the features of a base class, there is a chance that base class features are similar to derived class features, resulting in ambiguity for the JVM. The super keyword must be used to distinguish between base class features and derived class features.
super() and super(..) are used to establish communication between the constructors of the base class and the derived class.
On the other hand, this() and this(...) are used to establish communication between the constructors of the present class.
This can be used to differentiate between class variables and formal method or constructor parameters.
this() can be used to invoke one constructor from within another constructor without creating multiple instances of the same class.
Java's "this" and "super" keywords are effective instruments for object manipulation and class hierarchy navigation. By utilizing the capabilities of these keywords, you can avoid naming conflicts, distinguish between variables and parameters, effectively invoke constructors, and gain access to parent class members. You now have a firm understanding of how to unleash the power of the "this" and "super" keywords in Java programming through the use of examples and explanations.
Q: How does the "this" keyword enhance object-oriented programming in Java?
A. This keyword in Java is essential to object-oriented programming because it provides a reference to the current object. It facilitates self-reference within methods, enables method chaining for fluent interfaces, permits the distinction between instance variables and method parameters, and assists in the invocation of constructors.
Q: Can we use the "this" and "super" keywords interchangeably?
A: No, the "this" and "super" keywords serve different purposes. "This" refers to the current object, while "super" references the parent class. Their usage depends on the context and the specific functionality you intend to achieve.
Q: In static methods, is it possible to use 'this' and 'super'?
A: Static methods do not have access to 'this' and 'super' keywords. The pairing that works is as follows: instance methods can directly access both instance variables and methods, as well as static variables and methods. However, 'this' and 'super', which are inherently tied to object instances, are not available for use within static methods.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.