-1

A final variable points to an instance. I wanted to see what would happen if I changed the reference of the object to null. I am very surprised that there is no exception nor "is null" printed out. It is as if the line of code a = null; has been ignored.

output:

myFoo.name? haha

public class TryJava {
    class InnerFoo {
        public InnerFoo(String name) {
            super();
            this.myName = name;
        }
        String myName;      
        boolean isStarted;
    }
    InnerFoo a = new InnerFoo("haha");
    final InnerFoo myFoo = a;
    void bar() {
        a = null; // IGNORED???
        System.out.println("myFoo.name? " + (myFoo != null ? myFoo.myName : " is null "));
    }
    public static void main(String[] args) {
        TryJava tj = new TryJava();
        tj.bar();
    }

}
likejudo
  • 2,946
  • 6
  • 45
  • 90

2 Answers2

4

You changed what a refers to, sure. But myFoo still refers to an instance.

Jonathon Reinhart
  • 124,861
  • 31
  • 240
  • 314
1

There is no exception because final variable myFoo is still references to InnerFoo("haha") even thought refrence a is point to null.For example:at first variable a is refrencing to InnerFoo("haha').Then variable myFoo is refrence to same Instance InnerFoo('haha') by using refrence 'a'.When refrence 'a' assign null;myFoo is still refrencence to the InnerFoo('haha').please study about how object refrence work.

sawyinwaimon
  • 699
  • 1
  • 6
  • 14