Results 1 to 3 of 3
  1. #1
    BenH is offline Member
    Join Date
    Dec 2011
    Posts
    48
    Rep Power
    0

    Default What does "this" do?

    Hi there!

    I am studying the keyword "this". What exactly does it do? I am confused.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default Re: What does "this" do?

    In other word this keyword is useful when you need to refer an instance of a class from its method. So you can use it to avoid name conflict with instance and local variables. Go through the sample code with the comments below.

    Java Code:
    public class ThisKeywordDemo {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Multiplication obj = new Multiplication(12, 12);
    		System.out.println("Multiplication is: " + obj.MultiValue());
    	}
    
    }
    
    class Multiplication {
    	// Declare two instance variables
    	int iNum1;
    	int iNum2;
    	
    	// Constructor with two local variables with the same names 
    	// as instance variables of the class
    	public Multiplication(int iNum1, int iNum2) {
    		// So here we are going to initialize instance variables to the same value
    		// as local variables in the constructor. But how?
    		
    		this.iNum1 = iNum1;
    		this.iNum2 = iNum2;
    		
    		// Once you run the code and see the result, change the instance variable
    		// names into different and assign the value from the local variables without
    		// using the 'this' keyord. Compile the code ans run.
    	}
    	
    	public int MultiValue() {
    		// Here I haven't use 'this' keyword. Why?
    		return (iNum1 * iNum2);
    	}
    }

Similar Threads

  1. Replies: 1
    Last Post: 02-01-2012, 08:37 PM
  2. Replies: 5
    Last Post: 12-21-2011, 06:44 PM
  3. Replies: 1
    Last Post: 01-21-2010, 09:20 AM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •