why i can interchange field values inside a class using class reference
but can't interchange the references themselves
Here is the code of the class i have written
class Demo
{
int x,y;
Demo(int a,int b){x=a;y=b;}
public void swap(Demo ref) // interchanges field values of x and y
{
int temp;
temp=ref.x;
ref.x=ref.y;
ref.y=temp;
}
public void change(Demo ref1,Demo ref2) // supposed to interchange to
class variables of Demo class
{
Demo temp = ref1;
ref1 = ref2;
ref2 = temp;
}
}
swap method works fine i.e. interchange values of x and y.
Now, I have two questions here:
how the swap method is able to change the actual data passed to it? (I
have read that their is no pass by reference in Java.)
why change method does not interchange class references?
No comments:
Post a Comment