简体   繁体   English

OCJP的误解

[英]OCJP misunderstanding

I'm preparing to take OCJP exam and I have a tricky question. 我正在准备参加OCJP考试,但有一个棘手的问题。 I don't know why the correct answer is the next one : "B. 300-300-100-100-100" The question sounds like this: 我不知道为什么正确的答案是下一个:“ 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.    }

Frankly speaking I was expected that correct answer should be "A. 300-100-100-100-100" because at line 15 foo reference is changed to a new Foo object which has as instance variable x=100 and I don't know why at line 22 foo reference is to the "old object" with instance variable x=300 坦白地说,我期望正确的答案应该是“ A. 300-100-100-100-100-100”,因为在第15行,foo引用已更改为一个新的Foo对象,该对象具有实例变量x = 100,但我不知道为什么在第22行,foo引用是使用实例变量x = 300的“旧对象”

Can someone explain me why? 有人可以解释我为什么吗? Thanks! 谢谢!

Explaining inline : 内联解释:

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.        }

在第24行上更改了对foo变量的引用。在第15行上没有更改。因为原始foo被静态方法fooBar的本地foo变量隐藏。

This is how objects work in Java 这就是Java中对象的工作方式

Foo fooBoo = fooBar(foo); // here foo ---> 300

//function fooBar call //函数fooBar调用

foo = new Foo(100); 

This line will create new foo object pointing to 100 so it will look like this 该行将创建指向100的新foo对象,因此它将如下所示

foo (passed to method) ----> 300
foo (created inside method) ---> 100

That is why the value is not changing in that step 这就是为什么价值在那一步没有变化的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM