top

Search

Java Tutorial

.

UpGrad

Java Tutorial

This and Super Keyword in Java

Introduction

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)

Overview

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.

What is this Keyword in Java?

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.

Uses of the "this" Keyword in Java

The "this" keyword in Java serves several purposes, including:

  1. Differentiating Between Instance Variables and Parameters: When a parameter is called the same as an instance variable, "this" is used to specify that we are referring to the instance variable.

  2. Invoking Other Constructors: The "this" keyword can be used to invoke another constructor within the same class. This enables constructor chaining and reduces code duplication.

  3. Passing the Current Object: "this" can be passed as an argument to other methods or constructors to provide a reference to the current object.

  4. It is possible to use it to refer to the variables that are associated with the active class instance.

  5. It is possible to use it to return the instance of the currently active class from any of the instance methods that the class provides.

  6. It is possible to use it to access instance variables as well as static variables associated with the current instance.

  7. The “this keyword is put to use in the process of starting a constructor for the currently active class.

  8. It is possible to use the “this” keyword to call the methods of the currently active class.

Example of the "this" Keyword in Java

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.

What is the "super" Keyword in Java?

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.

Uses of the "super" Keyword in Java

The "super" keyword finds its utility in several scenarios:

  1. Invoking Parent Class Constructors: In a subclass, the "super" keyword is used to invoke the constructor of the parent class. This is essential when the parent class has a parameterized constructor that needs to be executed.

  2. Accessing Overridden Methods: When a subclass overrides a method from the parent class, the "super" keyword can be used to invoke the parent class's version of the method.

  3. Referencing Parent Class Variables: If a subclass has a variable with the same name as a variable in the parent class, the "super" keyword can be used to access the parent class's variable.

Examples of the "super" Keyword in Java

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.

Difference between super keyword and this keyword in java in tabular form

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

Similarities Between the "this" and "super" Keywords in Java

While the "this" and "super" keywords have distinct functionalities, they also share some similarities:

  1. They both assist in maintaining code readability and avoiding naming conflicts.

  2. The this and super keyword in Java constructors can be used to invoke other constructors.

  3. They contribute to the concept of inheritance in Java.

Can We Use Both "this()" and "super()" in the Same Constructor?

Yes, Java permits both "this()" and "super()" to be used in the same constructor. However, specific principles must be followed:

  1. The invocation of "this()" or "super()" must be the first line of the constructor.

  2. Both are responsible for invoking constructors, so they cannot be used in the same constructor.

  3. "this()" can invoke other constructors in the same class, whereas "super()" invokes the constructor of the parent class.

Important Points About "this()" and "super()" in Java

Here are some essential points to consider when using the "this()" and "super()" keywords in Java:

  1. "this()" and "super()" must be the first statements in a constructor.

  2. "this()" can only be used to invoke other constructors within the same class, while "super()" invokes the parent class constructor.

  3. If neither "this()" nor "super()" is used, the default constructor of the parent class is implicitly called.

  4. Recursive invocations of "this()" or "super()" are not allowed.

This and super keyword in java interview questions

  1. When do you need a super keyword?

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.

  1. How do you differentiate between this(), this(..), super(), and super(..)?

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.

  1. How is this. (this dot) different from this() (this off)?

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.

Conclusion

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.

FAQs:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *