JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Wednesday, 12 November 2014

this Keyword


"this" refers to present class members(instance variable,method,Constructor).local variable are accessible only in that particular method,Constructor where it is declared. if the name of instance variable and local variable are same, by default it will call the local variable  not the instance variable ,so how to refer the instance variable ,for this purpose “this” keyword is used. Here is an
Example of "this" for referencing instance variable,member and constructor of the present class :

class Present
{
int x; //instance variable
Present() //default constructor
{
this(10); //calls the parameterized constructor and passes the value 10
this.presentMethod();
}
//Local variable x gets 10 and it is stored in instance variable x
Present(int x)
{
//initializing value of local variable(x) to instance variable(this.x)
this.x=x;
}
void presentMethod()
{
System.out.print("Value of x is : "+x);
}
}

class This
{
public static void main(String args[])
{
Present p=new Present();
}
}

No comments:

Post a Comment

Designed By Blogger Templates