Page 1 of 1

"this" keyword in java Rate Topic: -----

#1 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Posted 25 February 2010 - 08:11 AM

*
POPULAR

"this" keyword in java
Hello everyone
In this tutorial
I am going to teach something interesting about the "this" keyword in java


Before this
Keep into mind that
Whenever we are creating an object, the copies of the instance variables are created for each object
for example in the following example I am creating two objects called td and td1
and in the class there are two instance variables called int a and int b.
Now what I am saying is that there will be two separate objects and for those separate objects
there will be separate variables int a and int b
This diagram elaborates more
Attached Image
Now that you got this we will move to our point
now when we use this keyword we are referring to the current object
now look at the program
Using this keyword with constructors
/* A program to demonstrate the use of this keyword 
Developer: Prasad Kharkar
Date	 : 25th February 2010
*/
class ThisDemo1
{
	int a = 0;
	int b = 0;
	ThisDemo1(int x, int y)
	{
	this.a = x;
	this.b = y;
	}
	public static void main(String [] args)
	{
	ThisDemo1 td = new ThisDemo1(10,12);
	ThisDemo1 td1 = new ThisDemo1(100,23);
	System.out.println(td.a); // prints 10
	System.out.println(td.B)/>; // prints 12
	System.out.println(td1.a);// prints 100
	System.out.println(td1.B)/>;// prints 23
	}
}

when we compile and run the program we get the output as

Quote

F:\Java\Concepts\DeclarationAndAccessControl>java ThisDemo1
10
12
100
23

Now we will look step by step
  • When we created the object td then the constructor was called for td
  • The respective values are passed to the copies of the instance variables of that object (as shown in the figure)
  • In the constructor using this.a = x and this.b = y, we copied the values into the instance variables
  • using System.out.println() statements we confirmed that those values referred to respective objects


Chaining of constructors using this keyword
Now what is chaining?
this is nothing but calling of one constructor from other constructor.
This is possible by using this keyword
Now look at the following program
/* A Program to demonstrate the use of This keyword
Developed By : Prasad kharkar
*/
class ThisDemo
{
	public ThisDemo()
	{
		this(10);
		System.out.println("First Constructor");
	}
	public ThisDemo(int a) // overloaded constructor
	{
		this(10,20);
		System.out.println("Second Constructor");
	}

    public ThisDemo( int a, int B)/> // another overloaded constructor
	{
		this("Prasad");
		System.out.println("Third Constructor");
	}
	public ThisDemo(String s) // and still another
	{
		System.out.println("Fourth Constructor");
	}


	public static void main(String args[])
	{
	ThisDemo first = new ThisDemo(); // one object should be created so that we can access other constructos through the constructor which is called first 
	}
}

This is interesting
Now this is the output of the program

Quote

F:\Java\Concepts\DeclarationAndAccessControl>java ThisDemo
Fourth Constructor
Third Constructor
Second Constructor
First Constructor

now what happened here?
let us go step by step
  • When the object is created then the respective constructor(No argument constructor) gets called
  • The control comes to the first line in the constructor where it encounter with "this(10)" statement
  • Hence it calls the constructor that accepts one integer argument
  • Again the control comes to the this(10,20) statement and again it jumps to the constructor which takes two integer arguments
  • Again the same thing, I need not explain it anymore, you will get bored
  • Now the control is in the constructor which takes string argument
  • here there is no this keyword
  • hence the constructor gets executed and control goes back to the calling constructor
  • This process continues till the first this keyword was encountered

Well this is the total procedure
I hope you got this thoroughly
similarly we can call methods using this keywordthis.someMethod();
Note that here we have called all the constructors using one object only

Using this with instance variables
well we already have used it
hehehe :rolleyes:
just look at the part of the code
ThisDemo1(int x, int y)
	{
	this.a = x;
	this.b = y;
	}

I need not elaborate this more

Now there are two most important points regarding this
  • Whenever we are using this in a constructor or a method for calling , then we must call it in the first line of method, otherwise it gives compile time error, but as KYA sir has explained we can write this for assignments anywhere
    this is code given by him
    public class Set {
        
        protected int a;
            public Set(){
                    System.out.println();
                    this.a = 10;
            }
            
            public int getA() {return a;}
            
            public static void main(String [] args){
                    Set set = new Set();
                    Setter s = new Setter();
                    System.out.println(s.getA());
                    System.out.println(set.getA());
            }
    }
    
    class Setter extends Set{
            public Setter(){
                    super();
                    this.a = 15;
            }
    }
    


  • We cannot write super and this in the same method as both need to be written in the first line

to know more about the super keyword, check out this tutorial by japanir sir.
Hope this tutorial was useful to you
Have a great time ahead!!

This post has been edited by pdkharkar: 25 February 2010 - 04:37 PM


Is This A Good Question/Topic? 8
  • +

Replies To: "this" keyword in java

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3116
  • View blog
  • Posts: 19,154
  • Joined: 14-September 07

Posted 25 February 2010 - 09:22 AM

this doesn't necessarily have to be in the first line in a file. You can have super() and then this assignments, example:

public class Set {
    
    protected int a;
	public Set(){
		System.out.println();
		this.a = 10;
	}
	
	public int getA() {return a;}
	
	public static void main(String [] args){
		Set set = new Set();
		Setter s = new Setter();
		System.out.println(s.getA());
		System.out.println(set.getA());
	}
}

class Setter extends Set{
	public Setter(){
		super();
		this.a = 15;
	}
}


Was This Post Helpful? 2
  • +
  • -

#3 pdkharkar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 63
  • View blog
  • Posts: 345
  • Joined: 19-January 09

Posted 25 February 2010 - 04:28 PM

thank you sir for the correction
I should have written that calling should be in the first line
Was This Post Helpful? 0
  • +
  • -

#4 XRaizeX  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 20
  • Joined: 20-March 10

Posted 23 March 2010 - 09:03 PM

Wow, i was just asking one of my teachers today about the this statement.
I thought someone was just being lazy. This makes a lot more sense now thank you
and also about your code with the output of:

Quote

F:\Java\Concepts\DeclarationAndAccessControl>java ThisDemo
Fourth Constructor
Third Constructor
Second Constructor
First Constructor


It prints them backwards o.o?
This looks like recursion to me. am i right?
Was This Post Helpful? 0
  • +
  • -

#5 sumit kothalikar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 27-February 10

Posted 30 March 2010 - 03:24 AM

View Postpdkharkar, on 25 February 2010 - 07:11 AM, said:

"this" keyword in java
Hello everyone
In this tutorial
I am going to teach something interesting about the "this" keyword in java


Before this
Keep into mind that
Whenever we are creating an object, the copies of the instance variables are created for each object
for example in the following example I am creating two objects called td and td1
and in the class there are two instance variables called int a and int b.
Now what I am saying is that there will be two separate objects and for those separate objects
there will be separate variables int a and int b
This diagram elaborates more
Attachment Untitled.png
Now that you got this we will move to our point
now when we use this keyword we are referring to the current object
now look at the program
Using this keyword with constructors
/* A program to demonstrate the use of this keyword 
Developer: Prasad Kharkar
Date	 : 25th February 2010
*/
class ThisDemo1
{
	int a = 0;
	int b = 0;
	ThisDemo1(int x, int y)
	{
	this.a = x;
	this.b = y;
	}
	public static void main(String [] args)
	{
	ThisDemo1 td = new ThisDemo1(10,12);
	ThisDemo1 td1 = new ThisDemo1(100,23);
	System.out.println(td.a); // prints 10
	System.out.println(td.B)/>; // prints 12
	System.out.println(td1.a);// prints 100
	System.out.println(td1.B)/>;// prints 23
	}
}

when we compile and run the program we get the output as

Quote

F:\Java\Concepts\DeclarationAndAccessControl>java ThisDemo1
10
12
100
23

Now we will look step by step
  • When we created the object td then the constructor was called for td
  • The respective values are passed to the copies of the instance variables of that object (as shown in the figure)
  • In the constructor using this.a = x and this.b = y, we copied the values into the instance variables
  • using System.out.println() statements we confirmed that those values referred to respective objects


Chaining of constructors using this keyword
Now what is chaining?
this is nothing but calling of one constructor from other constructor.
This is possible by using this keyword
Now look at the following program
/* A Program to demonstrate the use of This keyword
Developed By : Prasad kharkar
*/
class ThisDemo
{
	public ThisDemo()
	{
		this(10);
		System.out.println("First Constructor");
	}
	public ThisDemo(int a) // overloaded constructor
	{
		this(10,20);
		System.out.println("Second Constructor");
	}

    public ThisDemo( int a, int B)/> // another overloaded constructor
	{
		this("Prasad");
		System.out.println("Third Constructor");
	}
	public ThisDemo(String s) // and still another
	{
		System.out.println("Fourth Constructor");
	}


	public static void main(String args[])
	{
	ThisDemo first = new ThisDemo(); // one object should be created so that we can access other constructos through the constructor which is called first 
	}
}

This is interesting
Now this is the output of the program

Quote

F:\Java\Concepts\DeclarationAndAccessControl>java ThisDemo
Fourth Constructor
Third Constructor
Second Constructor
First Constructor

now what happened here?
let us go step by step
  • When the object is created then the respective constructor(No argument constructor) gets called
  • The control comes to the first line in the constructor where it encounter with "this(10)" statement
  • Hence it calls the constructor that accepts one integer argument
  • Again the control comes to the this(10,20) statement and again it jumps to the constructor which takes two integer arguments
  • Again the same thing, I need not explain it anymore, you will get bored
  • Now the control is in the constructor which takes string argument
  • here there is no this keyword
  • hence the constructor gets executed and control goes back to the calling constructor
  • This process continues till the first this keyword was encountered

Well this is the total procedure
I hope you got this thoroughly
similarly we can call methods using this keywordthis.someMethod();
Note that here we have called all the constructors using one object only

Using this with instance variables
well we already have used it
hehehe :rolleyes:
just look at the part of the code
ThisDemo1(int x, int y)
	{
	this.a = x;
	this.b = y;
	}

I need not elaborate this more

Now there are two most important points regarding this
  • Whenever we are using this in a constructor or a method for calling , then we must call it in the first line of method, otherwise it gives compile time error, but as KYA sir has explained we can write this for assignments anywhere
    this is code given by him
    public class Set {
        
        protected int a;
            public Set(){
                    System.out.println();
                    this.a = 10;
            }
            
            public int getA() {return a;}
            
            public static void main(String [] args){
                    Set set = new Set();
                    Setter s = new Setter();
                    System.out.println(s.getA());
                    System.out.println(set.getA());
            }
    }
    
    class Setter extends Set{
            public Setter(){
                    super();
                    this.a = 15;
            }
    }
    


  • We cannot write super and this in the same method as both need to be written in the first line

to know more about the super keyword, check out this tutorial by japanir sir.
Hope this tutorial was useful to you
Have a great time ahead!!

Was This Post Helpful? 0
  • +
  • -

#6 Guest_vipul_vj*


Reputation:

Posted 07 July 2011 - 09:19 AM

yes this was really helpful. :bigsmile: :bigsmile:
Was This Post Helpful? 1

Page 1 of 1