-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
  • 3,396
  • 6
  • 52
  • 107
  • 1
    You didn't change what myFoo is referencing, you only changed what a is referring to. Since you don't refer to a after that then there is no effect. – Nathan Hughes May 14 '16 at 14:40
  • 1
    This is nothing to do with final. `Object a = new Object(); Object b = a; a = null; System.out.println(b == null);`. – Oliver Charlesworth May 14 '16 at 14:40

2 Answers2

4

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

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
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
  • 739
  • 1
  • 6
  • 14