How can Java assignment be made to point to an object instead of making a copy?

前端 未结 5 1502
猫巷女王i
猫巷女王i 2020-12-03 08:25

In a class, I have:

private Foo bar;
public Constructor(Foo bar)
{
    this.bar = bar;
}

Instead of creating a copy of bar from the object

5条回答
  •  渐次进展
    2020-12-03 09:32

    Java never copies objects. It's easiest to think of in terms of for each "new" you will have one object instance--never more.

    People get REALLY CONFUSING when they discuss this in terms of pass by reference/pass by value, if you aren't amazingly familiar with what these terms mean, I suggest you ignore them and just remember that Java never copies objects.

    So java works exactly the way you wanted your first example to work, and this is a core part of OO Design--the fact that once you've instantiated an object, it's the same object for everyone using it.

    Dealing with primitives and references is a little different--since they aren't objects they are always copied--but the net effect is that java is just about always doing what you want it to do without extra syntax or confusing options.

提交回复
热议问题