简体   繁体   English

Java分配

[英]Java Assignments

I'm studying for an exam, and I'm looking through a sample program and I am confused. 我正在读考试,我正在查看示例程序而且我很困惑。 Here is the code: 这是代码:

public class Problem1 {
public static void f(A X)
{
    A Y = X;
    Y.key = X.key + 1;
}

public static void f(B X)
{
    B Y = new B();
    Y.key = X.key + 2; //Y.key = 12
    X = Y; //X points to Y? 
}

public static void main(String[] args)
{
    A P = new A();
    P.key = 3;
    B Q = new B();
    Q.key = 10;
    f(P);
    System.out.println(P.key);
    f(Q);
    System.out.println(Q.key);
    P = Q;
    f(P);
    System.out.println(P.key);
    }
    }

    class A
    {
public int key;
    }
    class B extends A 
    {

    }

I am fine with f(P). f(P)我很好。 The question I have is with f(Q). 我的问题是f(Q)。 I get that a new B named Y is made, and it's key is 12. The question I have is that, shouldn't X = Y point X to Y? 我得到一个名为Y的新B,它的关键是12.我的问题是,不应该X = Y点X到Y? Making Q's key value 12 rather than 10? 使Q的关键值为12而不是10? The code prints out 4,10,11. 代码打印出4,10,11。 I'm confused as to why it prints 10 rather than 12. 我很困惑为什么它打印10而不是12。

In java each variable of a class type, like P, Q, X etc, is a reference to an object (or null). 在java中,类类型的每个变量(如P,Q,X等)都是对对象的引用(或null)。 You can imagine that there's an object somewhere in memory and the variable points to it: 你可以想象在内存中有一个对象,变量指向它:
P -----> (P object)
When you call f(P) , the first f method receives a reference to the same object, but it is a different reference: 当你调用f(P) ,第一个f方法接收对同一个对象的引用,但它是一个不同的引用:
(main) P -----> (P object)
(f) X -----> (P object)
Then f makes yet another reference: 然后f再做一个参考:
(f) Y -----> (P object) And when it changes the key, it changes it in the same object. (f) Y -----> (P object)当它改变键时,它在同一个对象中改变它。

In the second case, f(Q) , the second f method again receives a (different) reference to the same object: 在第二种情况下, f(Q) ,第二个f方法再次接收对同一对象的(不同)引用:
(main) Q -----> (Q object)
(f) X -----> (Q object)
then it makes a new object: (f) Y -----> (Y object) 然后它创建一个新对象: (f) Y -----> (Y object)
then it changes the key in this object, and sets the X variable to point to this object: 然后它更改此对象中的键,并将X变量设置为指向此对象:
(f) X -----> (Y object, key=12)
however, in your main method, the Q variable hasn't changed: 但是,在您的main方法中,Q变量没有改变:
(main) Q -----> (Q object)
because X was just a copy of Q, it's not Q itself. 因为X只是Q的副本,所以不是Q本身。 So Q still points to the Q object, which was not modified, the Y object was modified. 所以Q仍然指向未修改的Q对象,Y对象被修改。

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

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