Tutorial Playlist
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.
Image Courtesy: RealToughCandy.com (Pexels)
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...