【问题标题】:Explain the questions mentioned in the comments [duplicate]解释评论中提到的问题[重复]
【发布时间】:2018-03-18 01:52:39
【问题描述】:
        class Bar{
        int barNum=28;
    }

    class Foo{
        Bar myBar = new Bar();
        void changeIt(Bar myBar){   //Here is object's reference is passed or the object is passed?
            myBar.barNum = 99;
            System.out.println("myBar.barNum in changeIt is " + myBar.barNum);
            myBar = new Bar();  //Is the old myBar object destroyed now and new myBar is referring to something new now?
            myBar.barNum = 420;
            System.out.println("myBar.barNum in changeIt is now "+myBar.barNum);
        }
        public static void main(String args[]){
            Foo f = new Foo();
            System.out.println("f.myBar.barNum is "+f.myBar.barNum);    //Explain f.myBar.barNum!
            f.changeIt(f.myBar);    //f.myBar refers to the object right? but we need to pass reference of the type Bar in changeIt!?
            System.out.println("f.myBar.barNum after changeIt is "+ f.myBar.barNum);    //How do you decide f will call which myBar.barNum?
        }
    }

请解释cmets中提到的问题 代码的输出是 f.myBar.barNum 为 28 myBar.bar 的变化数是 99 myBar.barNum 的变化现在是 420

f.myBar.barNum after changeIt is 99

【问题讨论】:

  • 1) 参考。 2)它可能现在被摧毁,以后或永远不会。 3) 现场访问。 4) 不,它是 Bar 类型的引用。 5)嗯?您无需决定,这只是字段设置的任何值。
  • 请再解释一下 5,myBar.barNum 的新值在创建 new bar() 后立即更改为 420;所以“f.myBar.barNum after changeIt is”的输出应该是 420 知道为什么是 99?

标签: java oop shadowing


【解决方案1】:

Java 在方法中传递对对象的引用。如果你愿意,你可以称它为指针。假设您在类 foo 中有对象 myBar 并将其传递给 change it 方法。它不传递对象本身,而是传递对该对象的引用(如果您愿意,可以使用指针)。

当你做 myBar.barNum = 99;这里 myBar 指向类 foo 中的实际对象 myBar 并更改其属性。

当你做 myBar = new Bar();这里的 myBar(我们看到它是一个对象的指针)开始指向一个不同于类 foo 的 myBar 的新 Bar 对象。您将其更改为 400,并且在该对象所在的上下文(方法)中,它是 400。当您离开该方法时,您将返回到原始对象所在的类 foo。由指向 99 的指针更改。

我希望我解释得当。如果一切都不叫 mybar 那就更容易理解了。因为在 myBar=new Bar() 行中,您实际上使用的是本地 mybar (在方法中)而不是全局的。例如:

Bar myBar = new Bar();
    void changeIt(Bar aBar){ 
        aBar.barNum = 99; //Here aBar is a pointer to the myBar above and changes it
        aBar = new Bar();  //Here aBar points to a new myBar instance
        a.barNum = 420; //This will be lost when you leave the method with the new instance created
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 2011-12-05
    • 2019-03-11
    相关资源
    最近更新 更多