/** * A Small example of the effect of call by sharing in Java * The point is that the passed reference is shared to the * subroutine. As a result, the subroutine can change the contents * of the shared reference. It can even change the reference inside * the subroutine, but it cannot change the reference in the caller. * This ends up looking a lot like the reference is passed by value. * * Created: Nov 2022 gtowell * @author gtowell */ public class CallShar { /** * A private class just so I have somethig to pass around whose internals I * can change. */ private class CSA { int iVal = 5; public String toString() { return String.format("CSA %d", iVal); } } public void share(CSA item) { item.iVal = 20; System.out.format("share 1: %s [%d]\n", item, System.identityHashCode(item)); item = new CSA(); item.iVal = 10; System.out.format("share 2: %s [%d]\n", item, System.identityHashCode(item)); } public void doo() { CSA iii = new CSA(); iii.iVal = 50; System.out.format("doo 1: %s [%d]\n", iii, System.identityHashCode(iii)); share(iii); System.out.format("doo 2: %s [%d]\n", iii, System.identityHashCode(iii)); } public static void main(String[] args) { (new CallShar()).doo(); } }