tobahhh
tobahhh

Reputation: 381

Java - Does an object resulting from a cast have the same reference value as the casted object?

I would like to draw images onto an already existing BufferedImage, like such:

    public static void drawImageOnTopOfOtherImage(BufferedImage a, BufferedImage b) {
        Graphics g = a.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(b);
    }

However, this instances two Graphics objects, g and g2. Graphics instances take up a lot of memory, so it is recommended that you dispose of them after you are done using them to decrease RAM usage, like such:

    g.dispose();

It would make a lot of sense to do something like this at the beginning for me:

    public static void drawImageOnTopOfOtherImage(BufferedImage a, BufferedImage b) {
        Graphics g = a.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
        g.dispose();
        g2.drawImage(b);
        g2.dispose();
    }

However, if an object resulting from a cast has the same reference value as the casted object, then this won't work.

So, here is my question: Does an object resulting from a cast have the same reference value as the casted object such that

    TypeA a = (TypeA) b;

is equal to

    TypeA a = (TypeA) b.clone();

? (Note that Graphics objects are not Cloneable, so this above does not work for Graphics objects)

Upvotes: 0

Views: 559

Answers (1)

etiescu
etiescu

Reputation: 103

I think you're confusing object references with object instances. In the above example you only have one instance of a Graphics object and have assigned it two references. This does not mean that there is 2 identical instances of a Graphics object held in memory so you don't need to worry about disposing of it.

This line of code is basically just adding another object reference to the same object. So now both g and g2 point to the same object in memory.

Graphics2D g2 = (Graphics2D) g

For the sake of conciseness though, you could implement your code like this without needing to assign a second reference to the same object:

public static void drawImageOnTopOfOtherImage(BufferedImage a, BufferedImage b) {
        Graphics2D g2 = (Graphics2D) a.getGraphics();
        g2.drawImage(b);
        g2.dispose();
}

Hope that clears things up

Upvotes: 4

Related Questions