Assignment in Java?

Say I set int A = int B. When I change A after, it does not change the value of B. But when I set SomeClass A = SomeClass B and change the contents of A (like a.cost) it also changes the value of B.cost. Can someone explain this to me?

I thought Java was assigned a value, not a reference?

+5
source share
4 answers

Yes, it is, but the value of A is a reference, not a copy of the object itself.

I like to give the following analogy ...

Suppose two people have my address: they are like two type variables Housein Java. Now one of them will come and blush my door. The second person will still see the red door if they visit:

House jonsHouse = new House(); // Even the variable jonsHouse is only a reference

House firstAddressCopy = jonsHouse; // Just a copy of the reference
House secondAddressCopy = jonsHouse; // Just a copy of the reference

firstAddressCopy.paintDoor(Color.Red);

Color color = secondAddressCopy.getDoorColor(); // Now color will be red

, , :

  • Java - -
  • ( ). - -
  • ( ) ,
+19

, Java , ?

" "? , "pass by value/reference"?

, Java, ( C/++). , A B , , , .

+2

A - . , , , .

A, B :

Foo a = new Foo();
Foo b = a;
a.bar = "bar"; // this is reflected in b
a = new Foo(); // b stays pointing to the previous Foo
a.bar = "baaar"; // b stays with a value of bar="bar"

(Java ). .)

+1

In Java, your variables can be divided into two categories: objects and everything else (int, long, byte, etc.).

The primitive type (int, long, etc.) contains any value that you assigned to it. An object variable, in contrast, contains a reference to an object somewhere. Therefore, if you assign one object variable to another, you copied the link, and points A and B point to the same object.

NOTE. Strings in Java are actually objects, not primitives, which are often assumed by beginners.

Hope this helps

0
source

All Articles