JavaRush /Java Blog /Random EN /Difference between this and super keywords in Java
grishin
Level 27
Харьков

Difference between this and super keywords in Java

Published in the Random EN group
thisand superare two special keywords in Java that represent the current instance of a class and its superclass, respectively. Java programmers often confuse these words and show little awareness of their special properties, which are often asked about in Java Core interviews. For example, a couple of questions that immediately come to mind are about thisand super, Is it possible to assign a different meaning to a keyword thisin Java? and what is the difference between keywords thisand superin Java. Do not know? Well, I’m not giving the answer here - it can be found at the end of the article. Difference between this and super keywords in Java - 1So, as I said at the beginning, the main difference between thisand superin Java is that thisthe current instance of a class represents, while superthe current instance of the parent class represents. Here is one example of using variables thisand super- you have probably already seen examples of calling constructors of one from another, the so-called. calling constructors in a chain, this is possible through the use of keywords thisand super. Inside a class, to call its no-argument constructor, is used this(), while super()it is used to call the no-argument constructor, or as it is also called, the default constructor of the parent class. By the way, in this way you can call not only a constructor without arguments, but also any other constructor by passing it the appropriate parameters. thisWe'll see an example of this use soon super. Also in thisJava superthey are used to access variables of a class instance and its parent. In fact, they can be accessed without the prefixes superand this, but only if in the current block such variables do not overlap with other variables, i.e. if it does not contain local variables with the same names, otherwise you will have to use names with prefixes, but this does not matter, because in this form they are even more readable. A classic example of this approach is to use thisa constructor inside that takes a parameter with the same name as the instance variable. Later in the article we will find out what other differences there are between superand this, and look at some examples of their use.

How this and super are similar

Before looking at the differences between keywords thisand super, let's look at some of their similarities:
  1. Both this, and superare non-static variables, so they cannot be used in a static context, which means they cannot be used in the main method. This will result in a compile-time error "a non-static variable thiscannot be referenced from a static context". The same thing happens if you use the keyword in the main method super.

  2. Both this, and supercan be used inside constructors to call other constructors in a chain, for example, this() and super() call the constructor without arguments of the inheriting and parent classes, respectively.
In the example below, we first pass a call from a no-argument constructor of class B to a constructor of the same class B that takes a single parameter of type String, which in turn super("")calls the one-argument constructor from the superclass.

class A{
   
    A(){
        System.out.println("Конструктор без аргументов класса A");
    }
   
    A(String args){
        System.out.println("Конструктор с одним аргументом класса A");
    }
}
 
class B extends A{
   
   B(){
        this(""); // вызов конструктора с одним аргументом класса B
        System.out.println("Конструктор без аргументов класса B");
    }
  
   B(String args){
        super(""); // вызов конструктора с одним аргументом класса A
        System.out.println("Конструктор с одним аргументом класса B");
    }
}
 
// Тест-класс и вывод 
public class Test {
   
    public static void main(String args[]) {      
       B b = new B();             
    }
 
}
Output: One-argument constructor of class A One-argument constructor of class B No-argument constructor of class B
  1. Inside the constructor this, and supermust appear above all other expressions, at the very beginning, otherwise the compiler will issue an error message. From which it follows that one constructor cannot contain both this(), and super().

Differences between super and this

Now we know how to use keywords superand thisunderstand what they are needed for. But there is another option for using these keywords that I did not mention - in Inner classes, where with their help it is very convenient to refer to an outer class using the Outer notation form. thisfor its current instance and Outer. super- for his parent. Don't forget to replace Outer with the name of the outer class. Now let's briefly list the main differences between keywords thisandsuper
  1. a variable thisrefers to the current instance of the class in which it is used, whereas it superrefers to the current instance of the parent class.

  2. Each constructor, in the absence of explicit calls to other constructors, implicitly calls super()the no-argument constructor of its parent class, but you always have the option of explicitly calling any other constructor with either this(), or super().
This is probably all that can be said about the differences between keywords thisand superin Java and how they are used in programs. As we have seen, their main purpose is to call one constructor from another and refer to instance variables declared in the current class and its parent class. Don't forget that these are not exactly ordinary variables, and now - the answer to my question, which I asked in the first paragraph. No, a variable thiscannot be assigned a new value because it is declared final. You can try to do this in the IDE - you will receive a compilation error "you cannot assign a new value to a variable this- it is declared final." Original article here .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION