Given:
class Product {
double price;
}
public class Test {
public void updatePrice(Product product, double price) {
price = price * 2;
product.price = product.price + price;
}
public static void main(String[] args) {
Product prt = new Product();
prt.price = 200;
double newPrice = 100;
Test t = new Test();
t.updatePrice(prt, newPrice);
System.out.println(prt.price + " : " + newPrice);
}
}
What is the result?
A.
200.0 : 100.0
B.
400.0 : 200.0
C.
400.0 : 100.0
D. Compilation fails.
题解
这题是在考 Java 永远为「pass by value」的概念。
第 20 行同时将基本型态的区域变量「newPrice」和对象参考的变量「prt」当作参数传给「updatePrice」方法。此时「newPrice」和「prt」的值都会被拷贝一份出来,「prt」的值为 Product 对象的参考(类似内存地址)。
「updatePrice」方法会将「newPrice」的值乘 2,再加给「prt」对象的「price」变量。
第 21 行将「prt」对象的「price」变量的值和「newPrice」变量的值输出。「prt」对象的「price」变量的值会是运行「updatePrice」方法时改变的结果,而「main」方法的「newPrice」变量并不会被改变。
