Search code examples
javaandroidobjectclass-structure

How do I pass an object in Java from Class B to Class C via Class A without duplication


Let's say I have 3 classes.

  • Class A (extends Activity)
    Class B
    Class C (extends View)

A creates a B object that holds a Bitmap. A also invalidates C. C's onDraw draws a Bitmap to its Canvas.

How do I draw the Bitmap that B holds without creating another Bitmap object in C? Note it is important for me to keep the same "class structure."

Here is the pseudo code. You can see this puts 2 Bitmap objects in memory. Thanks!

public class A extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        B b = new B();
        C c = (C) findViewById(R.id.c);

        c.passTheBitmap(b.bitmap);
        c.postInvalidate();
    }       
}

public class B {
    public Bitmap bitmap;
    public B(){
        bitmap = BitmapFactory.decodeResource(ActivityAContext.getResources(), R.drawable.fooBitmap);
    }
}

public class C extends View {
    public Bitmap bitmap;

    public C(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public passTheBitmap(Bitmap b) {
        bitmap = b;
    }
    @Override
    public void onDraw(Canvas canvas) {
        if (bitmap != null) {
            canvas.drawBitmap(bitmap, 0, 0, null);
        }
    }
}

Solution

  • I assume you think that the following line:

    c.passTheBitmap(b.bitmap);
    

    Would cause b.bitmap to get copied. It doesn't, so long as b.bitmap is not a primitive.

    In your code, the only way for there to be a second copy is if you use new to create a new object intentionally.

    E.g. in class C

    public passTheBitmap(Bitmap b) {
        bitmap = new Bitmap(b);
    }
    

    If you do as you have done:

    public passTheBitmap(Bitmap b) {
        bitmap = b;
    }
    

    ... then A.b.bitmap and C.bitmap will reference the same object in memory.

    If this was C++, then you have a valid concern - but in Java, what you are doing does not make a copy of the object being passed.

    HTH