Tuesday, February 18, 2014

this keyword in Java

'this' is a keyword in Java language which refers to current object. Current object means the instance on which any method is called. Suppose we have defined a class named Cl and two instance data members of this class is int a and b. One of the methods in the class is public void takeData(int a, int b) and 'obj' is the object created.

Suppose the function is defined like:

public void takeData(int a, int b)
{
 a=a;
b=b;
}

There will be no compile time or run time error but the data members will not get any value as compiler will fail to detect whether object members or function are getting value as name of both are same. In the above function, function members are setting values on object members so the codes should be like:

public void takeData(int a, int b)
{
 this.a=a;
this.b=b;
}

Here 'this' refers to the object 'obj' and we cann't use the name of the object here as there is no intimation about the object before or within the function body.

'this' can not be used inside any static function.

5 comments:

  1. Thanks Sir i was able to solve the program but like previous year could u please give some suggestions & most expected practical questions for this year's isc computer practical exam !

    ReplyDelete
    Replies
    1. Go through the previous year questions and you will get similar programs.

      Delete
  2. Sir can u please tell the meaning of each term in the command "System.out.println()"

    ReplyDelete
    Replies
    1. System is a class of lang package. 'out' is the object of PrintWriter class which is a static member in System class and println() is the function of PrintWriter class.

      Delete
  3. Can u write another program using number.plz

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner