Sunday, June 23, 2013

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. Couple of questions, which I remember about this and super keyword is  that, Can we reassign this in Java?  and difference between this and super keyword in Java. Do you want to try that? Ok, I am not giving answer now, rather I will let you know answer at the end of this post. As I said in first line, main difference between this and super in Java is that, this represent current instance of a class, while super represent current instance of 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. 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

difference between this and super keyword 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

Now we know how to use super and this keyword in Java, and comfortable with there intended use. One use of this keyword, which I didn't shown here is that you can also use them inside Inner classes, they are quite handy to get reference of outer class in Java, Outer.this and Outer.super can be used to get current instance of Outer class and it's parent in Java. Don't forget to replace Outer, with the name of enclosing class. Now In short, here are main differences between this and super keyword in Java

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

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

That's all on 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. Remember they are very special variables, and now answer of my question, which I asked in first paragraph. No, you can not assign 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".


Related Java tutorials and examples from Java67 blog

1 comment:

  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

Java67 Headline Animator