我准备参加OCJP考试,我有一个棘手的问题.我不知道为什么正确的答案是下一个:"B.300-300-100-100-100"问题听起来像这样:
1. class Foo {
2. private int x;
3. public Foo(int x) {
4. this.x = x;
5. }
6. public void setX(int x) {
7. this.x = x;
8. }
9. public int getX() {
10. return x;
11. }
12. }
13. public class Gamma {
14. static Foo fooBar(Foo foo) {
15. foo = new Foo(100);
16. return foo;
17. }
18. public static void main(String[] args) {
19. Foo foo = new Foo(300);
20. System.out.println(foo.getX() + "-");
21. Foo fooBoo = fooBar(foo);
22. System.out.println(foo.getX() + "-");
23. System.out.println(fooBoo.getX() + "-");
24. foo = fooBar(fooBoo);
25. System.out.println(foo.getX() + "-");
26. System.out.println(fooBoo.getX() + "-");
27. }
28. }
Run Code Online (Sandbox Code Playgroud)
坦率地说,我被期望正确的答案应该是"A. 300-100-100-100-100",因为在第15行foo引用被更改为一个新的Foo对象,其实例变量x = 100,我不知道为什么在第22行foo引用是具有实例变量x = 300的"旧对象"
有人能解释一下为什么吗?谢谢!
内联解释:
public static void main(String[] args) {
19. Foo foo = new Foo(300);
20. System.out.println(foo.getX() + "-"); // 300
21. Foo fooBoo = fooBar(foo); // foo is "unchanged" here
22. System.out.println(foo.getX() + "-"); // printing foo --> 300
23. System.out.println(fooBoo.getX() + "-"); // printing fooBoo --> 100
24. foo = fooBar(fooBoo); // changing foo and setting it to 100
25. System.out.println(foo.getX() + "-"); // So foo will be --> 100
26. System.out.println(fooBoo.getX() + "-");// fooBoo is already -->100
27. }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
361 次 |
最近记录: |