Difference between this and super keywords in Java

this and super are two special keywords in Java, which is used to represent current instance of a class and it's super class. Java Programmers often confused between them and not very familiar with there special properties, which is asked at various core Java interviews. A couple of questions, which I remember about this and super keyword is  that, Can we reassign this in Java?  and the difference between this and super keyword in Java. Do you want to try that? Ok, I am not giving the answer now, rather I will let you know the answer at the end of this post. 

As I said in the first line, the main difference between this and super in Java is that this represents current instance of a class, while super represents the current instance of the parent class. Now where does this and super variables used, well you might have seen examples of calling one constructor from other i.e. constructor chaining, that's achieved by using this and super keyword? 

You can use this() to call no-argument constructor of same class, while super() to call no argument or default constructor of parent class. By the way, call is not limited to only no argument constructor, you can call any constructor by passing appropriate parameters. We will see example of using this and super in a while. 

Another use of this and super in Java is for accessing instance variables of a class and it's parent. By the way, you can also access them even without prefixing super and this, if they are not ambiguous in current block e.g. if there is no local variable of same name exists in that block, but in case of ambiguity they provide explicit reference and are more readable. 

One of  the classic example of using this is inside a constructor, which accepts a parameter of same name as an instance variable. In this post, we will learn about more differences between super and this in Java and take a look at some of the use cases.




Similarities between this and super keywords in Java

Before seeing difference between this and super keywords in Java, let's see some similarities between them :

1. Both this and super are non static and can not be used in static context, which means you can not use this and super keyword inside main method in Java. Failing to do so will result in compiler error "non static variable this can not be referenced from static context". Same is true for using super keyword inside main method.

public static void main(String args[]) {       
     // compiler error - non static variable can not be referenced from static context
     System.out.println(this.name); 

}

2. Both this and super can be used in constructor chaining to call another constructor e.g. this() and super() respectively calls no argument constructor of child and parent class.

As shown in this example, we are first forwarding call from no argument constructor of B, to a constructor which accepts one String argument, which further call to super(""), a call to super class, one argument constructor.

class A{
   
    A(){
        System.out.println("A's no argument constructor");
    }
   
    A(String args){
        System.out.println("A's one argument constructor");
    }
}
 
class B extends A{
   
   B(){
        this(""); // calling one arg constructor of class B
        System.out.println("B's no argument constructor");
    }
  
   B(String args){
        super(""); // calling one argument constructor of class A
        System.out.println("B's one argument constructor");
    }
}
 
// Test Class and Output 
public class Test {
   
    public static void main(String args[]) {      
       B b = new B();             
    }
 
}
Output:
A's one argument constructor
B's one argument constructor
B's no argument constructor

3) If used them inside constructor than this and super must be first statement, otherwise compiler will complain. Which means you can not call this() and super() from same constructor.





super vs this in Java

Now we know how to use super and this keyword in Java, and comfortable with their intended use. One use of this keyword, which I didn't show here is that you can also use them inside Inner classes, they are quite handy to get the reference of the outer class in Java, Outer.this and Outer.super can be used to get the current instance of Outer class and it's a parent in Java. 

Don't forget to replace Outer, with the name of the enclosing class. Now In short, here are the main differences between this and super keyword in Java

1. this is used in the context of the class you are working on, while super is used to refer current instance of the parent class.

2. Every constructor by default calls super(), which is a call to the no-argument constructor of the parent class, but you can still call another constructor either explicitly by using this() or super().

Difference between this and super keywords in Java



difference between this and super keyword in JavaThat's all on the difference between this and super keyword in Java and How to use them in a Java program. We have seen calling another constructor from this and super keyword, and access member variables from current and parent class using them. 

Related Java tutorials and examples from the Java67 blog

Remember they are very special variables, and now answer of my question, which I asked in the first paragraph. No, you can not assign a new value to this variable, because it's final. You can try doing that in an IDE, you will get compiler error "can not assign a new value to final variable this".

8 comments:

  1. Interesting thing about this and super is that, they can be used as both method and variable. As said in article, if used as property, this represent current instance of a class, while super represent current instance of parent class. If used as method than this() is used to call no argument constructor of current class and super() is used to call, default constructor of parent class. Since constructor can be overloaded in Java, both this() and super() can also be overloaded to call respective constructors.

    ReplyDelete
  2. Very nice article...Very clear...Thx

    ReplyDelete
  3. very good article..very helpful.. thanx

    ReplyDelete
  4. "comfortable with their intended use" NOT "comfortable with there intended use"

    ReplyDelete
  5. we can access data member of parent class by using both this and super method,can any one clear my dought in their difference in this refrence

    ReplyDelete
  6. Couldn't make it halfway through your jumble of words with that horrendous grammar. It seems as if Java is your ONLY language.

    ReplyDelete
    Replies
    1. :-) phew .... Thanks for feedback, I'll edit this article.

      Delete
  7. Thank you for nice explanation..

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.