Mutable Reference
import java.io.*; import java.util.*; class Passref { // Just holds an integer. static class NotMuch { private int val; public NotMuch(int v) { val = v; } public void set(int v) { val = v; } public int get() { return val; } } public static void f1(NotMuch x) { x.set(45); x = new NotMuch(93); System.out.println("F1: " + x.get()); } public static void f2(NotMuch x) { x = new NotMuch(22); x.set(71); System.out.println("F2: " + x.get()); } public static void main(String [] args) { NotMuch alvin = new NotMuch(33); System.out.println("M1: " + alvin.get()); f1(alvin); System.out.println("M2: " + alvin.get()); f2(alvin); System.out.println("M3: " + alvin.get()); } }
Output:
M1: 33 F1: 93 M2: 45 F2: 71 M3: 45