0

When i do something lile this:

BufferedImage image = otherImage;

and image got affected otherImage get affected too?

David
  • 125
  • 8
  • 1
    Because that’s how all (except primitive) types in Java work. – Konrad Rudolph Oct 11 '20 at 21:38
  • Java variables are references, they point at an object, so assigning to a reference just makes it point at a different object, it doesn't create a new object. – tgdavies Oct 11 '20 at 21:39
  • So how then i can copy all data to a new image (with pixel by pixel raster coping)? – David Oct 11 '20 at 21:40
  • 1
    Does this answer your question? [How do you clone a BufferedImage](https://stackoverflow.com/questions/3514158/how-do-you-clone-a-bufferedimage) – maveriq Oct 11 '20 at 21:54

1 Answers1

1

This is how java memory model works. All objects placed in a heap. In your methods frames you only have an access to link that refers to this objects. You can manipulate with objects via this links. Statement that you posted says that you want take the second link and refer it to the same object as first link refers.

In case you need to copy object you need to care about that by yourself. There are a few ways to achieve this. For example you can make some copying method that will take initial object, take it’s fields, create a new instance, and set fields of this newly created object to previous extracted ones.

UPD: Take a look into this. There are explanations for your concrete case with BufferedImage. But seems like the question need to be updated and marked as duplicate.

maveriq
  • 456
  • 4
  • 14