SSSIT Computer Education Besides R.S.
Brothers Java
Show Room kphb-Hyderabad
This
“this “ is keyword of reference type
“this” is existed implicitly in every instance method of the class
“this” is always used to refer current object by hold its hash
code
Whenever both local and instance fields declare with the same in
order to make the differentiation between local and instance
fields, Then we have make use “this” for an instance field
“this” is not supported in the static context
1|Page
SSSIT Computer Education Besides R.S.Brothers Java
Show Room kphb-Hyderabad
Methods with Object Reference
Program to compare content of two objects
//Compare.java
class Sample
{ int x,y; //instance
void setData(int a,int b) //a,b are local
{ x=a; y=b; }
boolean compare(Sample o)
//non static mtd | instance mtd
{ if(x==o.x && y==o.y)
return true;
else
return false; }
2|Page
SSSIT Computer Education Besides R.S.Brothers Java
Show Room kphb-Hyderabad
public static void main(String args[ ])
{ Sample s1=new Sample( );
s1.setData(10,20 );
Sample s2=new Sample( );
s2.setData(110,220);
boolean b=s1.compare(s2);
if(b==true)
System.out.println("Both are Same");
else
System.out.println("Both are not Same");
}
}
Example 2: Program to copy data from one object to
another
//Copy Data From one to another
class Sample{
int x,y; //instance fields
void setData(int x,int y) //x,y formal acts as local
{ this.x=x; this.y=y; }
void copyData(Sample o) //instance mtd
{ x=o.x; y=o.y; }
void getData() //non static mtd
{ System.out.println("x val is : "+x);
System.out.println("y val is : "+y); }
3|Page
SSSIT Computer Education Besides R.S.Brothers Java
Show Room kphb-Hyderabad
public static void main(String args[ ])
{
Sample s1=new Sample( );
s1.setData(120,250);
Sample s2=new Sample( );
s2.copyData(s1);
System.out.println("Data from s1");
s1.getData();
System.out.println("Data From s2");
s2.getData();
}
}
4|Page