0

I'm a beginner to Java, and I wanted to know if you're allowed to set an object to null by using a method within its own class definition. Here's an example of what I mean: I have a class called MyList with the following method

public void close() {
    MyList me = this;
    me = null;
}

In other words, if I have an instance called

MyList list = new MyList();

and I call:

list.close();

Will this set list to null? Thanks!

C. Yoo
  • 87
  • 1
  • 11
  • 2
    I think this is an X-Y problem. Why do you want what you ask? What do you hope it will achieve? – John Bollinger Jan 02 '16 at 03:26
  • Java is not like C/C++: you shouldn't bother too much about "set an object to null" - when there are no references to the object - it will be eligible for GC. The only reason to bother about such is in case you have memory issues. – Nir Alfasi Jan 02 '16 at 03:35
  • Ah I see. I was just doing a coding challenge, and one of the method bodies they wanted me to complete was a method called close(), and they simply define it as "closes the list and releases all resources." Does that help with how I might achieve what they want? – C. Yoo Jan 03 '16 at 02:42
  • Does this answer your question? [Can "this" ever be null in Java?](https://stackoverflow.com/questions/3789528/can-this-ever-be-null-in-java) – pmaurais Mar 06 '20 at 16:46

2 Answers2

2

No, the method close() won't set list to null.

me is only a local variable, and assigning to it won't affect other variables.

I don't think what you want can be archieved.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

There is no way to change variables outside the class from inside methods. You can wrap a class into another class, and use that outer class to set the inner class reference to null on close():

interface MyInterface {
    void doSomething();
    void close();
}
class DoesAllTheWork implements MyInterface {
    public void doSomething() {
        ...
    }
    public void close() {
        ... // do nothing
    }
}
class Wrapper implements MyInterface {
    private MyInterface wrapped = new DoesAllTheWork();
    public void doSomething() {
        if (wrapped == null) {
            throw new IllegalStateException();
        }
        wrapped.doSomething();
    }
    public void close() {
        wrapped = null;
    }
}

Now you can do this:

MyInterface s = new Wrapper();
s.doSomething();
s.close(); // Sets "wrapped" object to null
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523