Java里面对象的传递是通过对象的引用,而引用又是用变量名表示的,但是注意变量名不是引用本身。如下示例程序:
变量c的重新赋值并不影响之前表示的引用(对象)。
/* * @(#)PassedReferenceWillNotChange.java 2014年5月7日 * * Copyright (c) 2014 Wu Owen. All rights reserved. */ package com.labj.main; /** * Passed object c is stored in B, when c is assigned to another object, object stored in B will not * change. * * @author owen */ public class PassedReferenceWillNotChange { public static void main(String[] args) { C c = new C(1); B b = new B(c); System.out.println("A.f()"); c = new C(2); // b.setC(c); b.g(); } } class B { C c; public B(C c) { this.c = c; } void g() { System.out.println("B.g()"); System.out.println("c.getId(): " + c.getId()); } void setC(C c) { this.c = c; } } class C { int id; public C(int id) { this.id = id; } int getId() { return id; } }