In order for this to work, you need to pass something that is a reference type instead of a value type. Instance primitives are always passed by value, but there is nothing preventing you from passing the instance - but this would require a redesign of your classes: Consider the following (c#-like pseudocode)...
public class Container
{
public int x;
}
... // some implementation in another class
Container myContainer = new Container();
myContainer.x = 0;
MyPrinter printer = new MyPrinter(myContainer);
printer.Print(); //Result is 0
myContainer.x ++;
MyPrinter.Print(); //Result is 1
This assumes that the MyPrinter
class knows what to do with a Container
instance.
What's going on here? Well a primitive, like int
is passed by value - which means that the program makes a copy when passing it into the method:
int x = 0;
MyPrinter printer = new MyPrinter(x); // Makes a copy of x, and passes the copy to MyPrinter
printer.Print(); //Expected result is 0 - correct
x++; // Increments the local variable, but not the copy
MyPrinter.Print(); //Expected result is 1 - incorrect because only the local variable is updated.
As opposed to:
Container myContainer = new Container();
myContainer.x = 0;
MyPrinter printer = new MyPrinter(myContainer); // Passes the reference to the same instance
printer.Print(); //Result is 0 - because it uses the variable attached to the instance
myContainer.x ++; // Increments the variable attached to the instance
MyPrinter.Print(); //Result is 1 - because the instance is still the same in both places - due to being passed by reference.