Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??
From Java The Complete Reference by Herbert Shildt 9th edition: "When you pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Keep in mind that when you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by theargument. This effectively means that objects act as if they are passed to methods by use of call-by-referen ce. Changes to the object inside the method do affect the object used as an argument."
package objectpassing;
public class PassObjectTest {
public static void main(String[] args) {
Obj1 o1 = new Obj1(9);
System.out.println(o1.getA());
o1.setA(3);
System.out.println(o1.getA());
System.out.println(sendObj1(o1).getA());
System.out.println(o1.getA());
}
public static Obj1 sendObj1(Obj1 o)
{
o.setA(2);
return o;
}
}
class Obj1
{
private int a;
Obj1(int num)
{
a=num;
}
void setA(int setnum)
{
a=setnum;
}
int getA()
{
return a;
}
}
OP: 9 3 2 2
FInal call to getA() shows original object field 'a' was changed in the call to method public static Obj1 sendObj1(Obj1 o).