Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance variable

 
venkataraman muthuvel
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

my code:

class ValHold{
public int i = 10;
}

public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.print( v.i );
}//End of amethod

public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.print(v.i);
System.out.print(i);
}//End of another

}

this code compile & run fine .

output is
10020

any exaplain is code

Thanks & regards venkat
 
Dan T
Ranch Hand
Posts: 66
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void another(ValHold v, int i){
i=0;
v.i = 20;

** sets i = 20 (this v refers to the v in amethod()

ValHold vh = new ValHold();
v = vh;

** this changes the reference ValHold v (the one in the parameter) from the reference it had with the v in the amethod(), to a new instance vh,
now v.i=10


System.out.print(v.i);

** prints out 10, as we stated from above

System.out.print(i);

** i never changed, only v.i was set to 20, so prints out 0

public void amethod(){
.
.
.
another(v,i);
System.out.print( v.i );
}

** returning from the another method, we have v.i = 20 which was set here

public void another(ValHold v, int i){
i=0;
v.i = 20;

hope this helps
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic