this and super Introduction

this and super keywords have special role to play in Java. this is used to refer to current class’s instance and super is used to refer the super class instance and constructor.
Both of them have two meanings and can be used as reference variable or constructor call. We shall see shortly how these keywords are used in multiple context using sample code.

this Keyword

this keyword stands for current class’s instance or constructor. Suppose, you create an object using new operator and then invoke a method on this instance,
Now if you want to access the member variables for this instance then use this keyword. Here are the usage scenario with sample code:

this as reference variable:

When used as a variable, “this” refers to the instance of the class on which the operation has been invoked.

	package example.java;
	class Foo{
		int a;
		void a() {
			this.a = 10; //line 5
			System.out.println("this.a: " + this.a);
		}
		public static void main(String[] args) {
			Foo f = new Foo(); //line 9
			f.a(); 
		}
	}

Output:
this.a: 10

In line 5 of the above program, this keyword refers to the instance created in line 9 of the program.

The Java Language Specification (JLS) mentions following text about this keyword:

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

this as constructor call:

When used as a method call, it refers to a constructor. This call can be placed only as a first line of any constructor of a class. When parameters are passed while invoking a constructor, the corresponding constructor is invoked.
We use this format when invoking overloaded constructors.

	package example.java;

	class Foo{
		Foo(){
			System.out.println("Blank");
		} 
		Foo(int a){
			this();
			System.out.println("a: " + a);
			// this(); causes compiler error
		} 
		Foo(int a, int b){
			this(a);
			System.out.println("a: " + a);
			System.out.println("b: " + b);
		} 
		public static void main(String[] args) {
			Foo f = new Foo(2,3);
		}
	}

Output:
Blank
a: 2
a: 2
b: 3

super Keyword

Similar to this keyword, super keyword also has multiple meanings as shown in following code examples.

super as reference variable:

As a reference variable, super refers to the instance of super class and can be used to invoke methods and access properties of super class as shown below:

	package example.java;

	class Foo{
		int a = 10;
		Foo(){
			System.out.println("Blank");
		}
		Foo(int a){
			System.out.println("a: " + a);
		}
	}

	public class Bar extends Foo{
		Bar(){
			super(10);
			System.out.println("Bar");
			System.out.println("Super class's variable: " + super.a);
		}
		public static void main(String[] args) {
			Bar b = new Bar();
		}
	}

Output:
a: 10
Bar
Super class’s variable: 10

super as constructor call:

The super keyword is used to refer to the super class’s constructor. As with this keyword, when parameters are passed to a super call, the corresponding constructor of super class is invoked.
The following code example shows how constructor of Bar class calls constructor of Foo class.

	package example.java;

	class Foo{
		Foo(){
			System.out.println("Blank");
		}
		Foo(int a){
			System.out.println("a: " + a);
		}
	}

	public class Bar extends Foo{
		Bar(){
			super(10);
			System.out.println("Bar");
		}

		public static void main(String[] args) {
			Bar b = new Bar();
		}
	}

Output:
a: 10
Bar

It is worth mentioning here that this() and super() have to be first statement of any constructor.

this and super as method arguments

We can pass this as a reference argument to a method like doThis(this) but the same can’t be done with the super keyword. The following code shows how this keyword is passed from one method to another (one being static and other being non-static)

public class Test{
   public void method1() {
       method2(this);
   }
   public static void method2(Test t){
      System.out.println("Received this as argument");
   }
}

As shown in the above code, method2 needs to specify the class named in the arguments list because it will be receiving an argument of type Test in the form of this keyword.

Bypassing the first statement rule

As stated in the above sections that the Java compiler forces you to place the call to this or super as the first statement of every constructor. If we don’t do it explicitly, the compiler implicitly inserts a call to super class’s no-arg constructor.

Many developers have raised concerns about not being able to execute some statements (pre-processing) before invoking this or super constructors. Some of the programs can benefit from the fact we can write expressions as part of method argument list. For e.g.

super(Arrays.asList(new Object[] { item }));

In the above statement, we are converting an array to List and then passing that List to the super class constructor. Similarly other expressions can be written which could be assignment, casting or arithmetic operations. But still, you may not be able to use very complex expressions spanning across multiple statements with this approach.

Read More: http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor

this and super keyword with inner classes

this keyword

In a non-static inner class member of a class, this keyword shall refer to the instance of the non-static inner class. Since a non-static inner class also has constructors, this keyword can be used in the same fashion as described in the above sections.

In order to access the instance of outer class from non-static inner class, we need to use MyOuter.this which will refer to the outer class instance used to construct the inner class.

For example

public class Outer {
     ....
    public class Inner {
        private int x;
        ....

        public void innerMethod(int x) {
             this.x = x;        //this refers to an instance of Outer.Inner

             Outer.this.x = x;  //Outer.this  refers to an instance of Outer

        }

    }
}

super keyword

The super keyword in a non-static inner class shall refer to the parent class of inner class. Since inner classes can also extend other classes by using the extends keyword, super keyword works in the similar fashion with inner classes as with top level classes.

If the non-static inner class doesn’t extend any other class explicitly then the super keyword shall refer to the instance of Object class which is the default parent of all classes.

References

1. Using the Keyword super
2. Difference between Super and this in Java
3. Using the this Keyword
4. this and super

this and super keywords admin Core Java
this and super Introduction this and super keywords have special role to play in Java. this is used to refer to current class's instance and super is used to refer the super class instance and constructor. Both of them have two meanings and can be used as reference variable or constructor...
<h2>this and super Introduction</h2> <p>this and super keywords have special role to play in Java. this is used to refer to current class's instance and super is used to refer the super class instance and constructor. Both of them have two meanings and can be used as reference variable or constructor call. We shall see shortly how these keywords are used in multiple context using sample code. <div id="toc"> 1. <a href="#thiskeyword">this Keyword</a> 2. <a href="#superkeyword">super Keyword</a> 3. <a href="#methodargs">this and super as method arguments</a> 4. <a href="#firststatement">Bypassing the first statement rule</a> 5. <a href="#innerclasses">this and super keyword with inner classes</a> 6. <a href="#references">References</a> </div> </p> <a name="thiskeyword"></a> <h2>this Keyword</h2> <p>this keyword stands for current class's instance or constructor. Suppose, you create an object using new operator and then invoke a method on this instance, Now if you want to access the member variables for this instance then use this keyword. Here are the usage scenario with sample code:</p> <h3>this as reference variable:</h3> When used as a variable, "this" refers to the instance of the class on which the operation has been invoked. 1 <blockquote> Output: this.a: 10 </blockquote> In line 5 of the above program, this keyword refers to the instance created in line 9 of the program. The Java Language Specification (JLS) mentions following text about this keyword: <blockquote>The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs. </blockquote> <h3>this as constructor call:</h3> <p>When used as a method call, it refers to a constructor. This call can be placed only as a first line of any constructor of a class. When parameters are passed while invoking a constructor, the corresponding constructor is invoked. We use this format when invoking overloaded constructors.</p> 1 <blockquote> Output: Blank a: 2 a: 2 b: 3 </blockquote> <a name="superkeyword"></a> <h2>super Keyword</h2> Similar to this keyword, super keyword also has multiple meanings as shown in following code examples. <h3>super as reference variable:</h3> As a reference variable, super refers to the instance of super class and can be used to invoke methods and access properties of super class as shown below: 1 <blockquote> Output: a: 10 Bar Super class's variable: 10 </blockquote> <h3>super as constructor call:</h3> <p>The super keyword is used to refer to the super class’s constructor. As with this keyword, when parameters are passed to a super call, the corresponding constructor of super class is invoked. The following code example shows how constructor of Bar class calls constructor of Foo class.</p> 1 <blockquote> Output: a: 10 Bar </blockquote> It is worth mentioning here that this() and super() have to be first statement of any constructor. <a name="methodargs"></a> <h2>this and super as method arguments</h2> We can pass this as a reference argument to a method like doThis(this) but the same can't be done with the super keyword. The following code shows how this keyword is passed from one method to another (one being static and other being non-static) 1 As shown in the above code, method2 needs to specify the class named in the arguments list because it will be receiving an argument of type Test in the form of this keyword. <a name="firststatement"></a> <h2>Bypassing the first statement rule</h2> As stated in the above sections that the Java compiler forces you to place the call to this or super as the first statement of every constructor. If we don't do it explicitly, the compiler implicitly inserts a call to super class's no-arg constructor. Many developers have raised concerns about not being able to execute some statements (pre-processing) before invoking this or super constructors. Some of the programs can benefit from the fact we can write expressions as part of method argument list. For e.g. super(Arrays.asList(new Object[] { item })); In the above statement, we are converting an <a href="http://www.javaexperience.com/differences-between-arraylist-and-vector/" title="Differences between ArrayList and Vector">array to List</a> and then passing that List to the super class constructor. Similarly other expressions can be written which could be assignment, casting or arithmetic operations. But still, you may not be able to use very complex expressions spanning across multiple statements with this approach. <strong>Read More:</strong> <a href="http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor">http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor</a> <a name="innerclasses"></a> <h2>this and super keyword with inner classes</h2> <h3>this keyword</h3> In a non-static inner class member of a class, this keyword shall refer to the instance of the non-static inner class. Since a non-static inner class also has constructors, this keyword can be used in the same fashion as described in the above sections. In order to access the instance of outer class from non-static inner class, we need to use MyOuter.this which will refer to the outer class instance used to construct the inner class. For example 1 <h3>super keyword</h3> The super keyword in a non-static inner class shall refer to the parent class of inner class. Since inner classes can also extend other classes by using the extends keyword, super keyword works in the similar fashion with inner classes as with top level classes. If the non-static inner class doesn't extend any other class explicitly then the super keyword shall refer to the instance of <a href="http://www.javaexperience.com/why-wait-notify-and-notifyall-methods-are-present-in-object-class/" title="Why wait, notify and notifyAll methods are present in Object class?">Object class</a> which is the default parent of all classes. <a name="references"></a> <h2>References</h2> 1. <a href="http://docs.oracle.com/javase/tutorial/java/IandI/super.html" target="_blank">Using the Keyword super</a> 2. <a href="http://www.coderanch.com/t/559849/java-programmer-SCJP/certification/Difference-Super-Java" target="_blank">Difference between Super and this in Java</a> 3. <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html" target="_blank">Using the this Keyword</a> 4. <a href="http://math.hws.edu/javanotes/c5/s6.html" target="_blank">this and super</a>
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.