Is it possible to set to null an instance of a cla

2019-02-18 04:36发布

Is it possible to set to null an instance of a class within the class. For example, could I do something like this

int main{
    //Create a new test object
    Test test = new Test();
    //Delete that object. This method should set the object "test" to null, 
    //thus allowing it to be called by the garbage collector.
    test.delete();

}


public class Test{

    public delete(){
        this = null;
    }
}

I have tried this and it does not work. Using "this = null" I get the error that the left hand side needs to be a variable. Is there a way to achieve something similar?

5条回答
Root(大扎)
2楼-- · 2019-02-18 05:14

You can do something like this

public class WrappedTest {
    private Test test;
    public Test getTest() { return test; }
    public void setTest(Test test) { this.test = test; }
    public void delete() { test = null; }
}
查看更多
祖国的老花朵
3楼-- · 2019-02-18 05:20

"this" is a final variable. you can not assign any values to it.

If you want to set the reference null you can do this

test = null;
查看更多
Summer. ? 凉城
4楼-- · 2019-02-18 05:23

this is a reference to the instance of your class. When you modify a reference variable, it only modifies that reference and nothing else. For example:

Integer a = new Integer(1);
Integer b = a;

a = new Integer(2);      //does NOT modify variable b

System.out.println(b);   //prints 1
查看更多
够拽才男人
5楼-- · 2019-02-18 05:28

An instance of an object doesn't know which references might be referring to it, so there's no way that code within the object can null those references. What you're asking for isn't possible(*).

* at least not without adding a pile of scaffolding to keep track of all the references, and somehow inform their owners that they should be nulled - in no way would it be "Just for convenience".

查看更多
我只想做你的唯一
6楼-- · 2019-02-18 05:28

Is it possible to set to null an instance of a class within the class?.

You cannot do this from the member methods of the same instance. So, this=null or that sort of thing will not work.

How come one set an instance to an null?

That question itself is wrong, we set references to null but not instances. Unused objects automatically garbage collected in java.

If you set test=null it will eventually gets garbage collected.

 int main{
    //Create a new test object
    Test test = new Test();
    // use the object through test
    test=null;
}
查看更多
登录 后发表回答