简体   繁体   中英

Java. Can i delete instance of class from method of this class?

public class Foo{
   public Foo(){}
   public void Method()
   {
       this = null; //doesn't work
   }
}

I know that in C# i can't do this, but may be can in Java?

nope , you can not do.

you will get below error.

The left-hand side of an assignment must be a variable

Can i delete instance of class from method of this class?

There is no instance of the class yet unless you've created it.

Foo foo=new Foo();

You can dereference foo by

foo=null;

Now the foo object which the foo reference points to on the heap will be collected by garbage collector

public class Foo{

    public static void main(String[] args)
    {
        Foo foo=new Foo();
        System.out.println(foo);
        foo=null;
        System.out.println(foo);
    }
}

Output

Temp@1a8c4e7
null

Can i delete instance of class from method of this class?

No. Because it doesn't make sense right. You didn't create any object so far and you are trying to dereference it..??

In Java, Memory management is handled by JVM and all the objects are destructed by JVM when they are no more referenced.

So you can not guarantee an instance to be deleted at specific time.

   public class Foo {
    public Foo() {
    }

    public void Method() {
        // some code
    }
}

public class Test {
 public static void main(String[] args){
   Foo foo = new Foo(); // Constructor-Instance created and referenced
     foo = null; // reference variable foo is made null.
  }
 }

Once foo is made null, the instance for Foo is available for GC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM