Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 910
eBehbahani Avatar asked Jun 04 '13 17:06

eBehbahani


People also ask

Can an instance of a class be null?

Longer answer: Instances cannot be null at all. Variables that are typed as references to the class can be set to null , but not instances.

Can you create an instance of a class within the same class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass.

Can an object of a class be null?

Technically, it will have a value of null. However, the C# compiler will not let you use the object until it has been explicitly assigned a value (even if that value is null ). no difference, both are null.

Can you set something to null in Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type.


2 Answers

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".

like image 186
RichieHindle Avatar answered Dec 14 '22 15:12

RichieHindle


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; }
}
like image 43
Zim-Zam O'Pootertoot Avatar answered Dec 14 '22 17:12

Zim-Zam O'Pootertoot