开发者

Problem with class instances, Android

I am trying to make a game for android I have a bitmap and canvas instance in my main class.

I have another instance of, lets say, renderer class. That renderer class is in the same package, but not the subclass of my main class.

If i pass the bitmap and canvas instance to a method of that renderer class and that method will draw that passed bitmap to the passed canvas, are the actual instances passed or new instance copies crea开发者_如何学Goted and then passed ? Well, i have tried and saw that actual instances were being passed. Because i was seeing the bitmap being drawn to the canvas.

Here is my question, why are the actual instances are passed ? if it was something like this ->


public class instanceTest
{
    static int num;

    static void numIncrementor(int number)
    {
        number++;
    }

    public static void main(String[] args)
    {
        num = 0;
        numIncrementor(num);
        System.out.println(num);
    }
}

Here, when i print the num, i will still get 0, but with other bitmap and canvas thing, i do send the actual instances. This got me really confused. Can someone explain it ? Or is it always the case with class objects unlike primitive types ? Does it make garbage collector go crazy ?

Thanks in advance, if you did not understand my engrish, tell and i will put pseudo codes here for clarification;


You should really read the Java tutorial before starting to write Java code.

In your example above you passed a primitive - so it's value is simply passed to the method, placed on the stack and that value is altered. That is how primitives work in Java. This means that your number variable only exists within the scope of the numIncrementor method - and does not effect what is outside.

Your actual code works with objects. When you pass an object you actually pass the reference to it on the heap. So every change you do to it will be done on the actual object. The only exception is that you cannot "re-assign" the object to something else since you only hold a reference to the heap - you can "re-assign" your reference to another location on the heap, but the original reference will continue to point to the original object.

As for your question on the garbage collector - no, it will not go crazy. It actually works pretty good. (There is more than one type of GC, but that is a whole different discussion).

Java does not use Copy Constructors - if you want to pass a copy of an object to a method, you should make it cloneable and pass a clone of it. But this is probably not what you need - note that Copy Constructors consume more resources than just passing the reference to the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜