Variables declared as static
are created once the first instance of the class are created, or the first reference to that variable is called. This means that the object will live for the whole application lifetime and there's no way they will be removed from memory unless you explicitly set to NULL
.
This being said, your static variable can be used in any way you want, but you need to be careful not to assign to it an object that you expect to deallocate. A simple example
public class Foo {
static MyObject object;
static void setObject(MyObject obj)
{
object = obj;
}
}
Using Foo.setObject(someObject)
would cause someObject
never to be deallocated, because the static
variable lives forever and is pointing to someObject
, hence it will never be garbage collected.
A more complicated example:
public class Foo {
static MyObject object;
static void setBar(Bar bar)
{
object.bar = bar;
}
}
Here the story is the same. bar
will not be garbage collected because object.bar
is pointing to it, and object
is static
. This is what happens in the example you pasted.
label.setBackgroundDrawable(sBackground);
public class Label { // just to illustrate the concept
void setBackgroundDrawable(Drawable d) {
// If d is static, callback is pointing to the label and will not be deallocated
d.callback = this;
}
}
Of course, you would need to know how setBackgroundDrawable
works (which I didn't until reading the link you posted) in order to draw the conclusion that it could lead to a leak.