Results 1 to 3 of 3
Thread: What does "this" do?
- 03-04-2012, 12:31 AM #1
Member
- Join Date
- Dec 2011
- Posts
- 48
- Rep Power
- 0
-
Re: What does "this" do?
It references the current object.
For more, please have a look here: Using the this keyword.
- 03-04-2012, 04:11 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
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
-
loop "play again" in an 8 ball game , loops but wont let me answer my "out.print"
By IareSmart in forum New To JavaReplies: 1Last Post: 02-01-2012, 08:37 PM -
Got struck with this :- " Exception in thread "main" java.lang.NullPointerException"
By Vermont in forum New To JavaReplies: 5Last Post: 12-21-2011, 06:44 PM -
How to change my form design from "metal" to "nimbus" in Netbeans 6.7.1?
By mlibot in forum New To JavaReplies: 1Last Post: 01-21-2010, 09:20 AM -
MoneyOut.println("It took you (whats wrong?>",year,"<WW?) years to repay the loan")
By soc86 in forum New To JavaReplies: 2Last Post: 01-24-2009, 06:56 PM -
the dollar sign "$", prints like any other normal char in java like "a" or "*" ?
By lse123 in forum New To JavaReplies: 1Last Post: 10-20-2008, 07:35 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks