0

can we make a instance reference null in the class itself? like bellow:

public class ClassA{
    public void clear(){
        //make this class be null
    }
}

ClassA a = new ClassA();
a.clear();
//now a == null

can we implement this methord in C# or Java

Yeezh
  • 141
  • 1
  • 7
  • I am pretty sure you can only dump all objects by setting them to null in your class and garbage collecting. Making it null has to be done by the variable holder – ArsenArsen Sep 11 '16 at 09:44
  • See also http://stackoverflow.com/questions/21283346/how-to-set-the-instance-to-null-inside-class and http://stackoverflow.com/questions/34562258/setting-an-object-to-null-within-its-own-class-definition – Tunaki Sep 11 '16 at 09:50

2 Answers2

2

Short answer: No.

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. There can be many variables referring to the same instance. The instance has no way of knowing about those variables, so there's no way for it to reach out and set them to null.

Instead, you could have a method that returns null with the return type of the class:

public ClassA clear() {
    return null;
}

...which the caller could use

foo = foo.clear();

But it doesn't really serve any purpose, the caller could just as easily do

foo = null;

Side note:

In .Net (since you mention C#), you might look at the IDisposable interface.

In Java, you might look at AutoCloseable.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0
public class ClassA
{
  private ClassA obj = new ClassA();
  public void clear(){
        obj = null;
    }
}

Is this what you are expecting, References of an object can be set to null.

kushagra mittal
  • 343
  • 5
  • 17