-1

I have below code, where I have a final inner class.

So as per final it should not allow to re-assign it a value. But it still does. Please explain:

public class POJO {

    public final String vNew;

    public POJO () {
        vNew="hello";
    }

    final class abc {
        String name="abc";
    }

    public static void main(String[] args) {
        POJO vPOJO = new POJO();
        POJO.abc in=vPOJO.new abc();  
        System.out.println(in.name);
        in.name="World";
        System.out.println(in.name);
        in=vPOJO.new abc();
        System.out.println(in.name);
    }    
}

Output is

abc
World
abc

The code POJO.abc in=vPOJO.new abc(); and in=vPOJO.new abc(); is re-assignment isn't it.

Just not sure as it uses the handle of outer non final class, makes it work.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
ViS
  • 1,357
  • 1
  • 17
  • 36
  • duplicate of [Use of final class in Java](https://stackoverflow.com/questions/5181578/use-of-final-class-in-java) – matoni Jul 11 '17 at 10:50

2 Answers2

6

If a class is final, it just means it can't be extended.

If you want to prevent reassignment, make the variable final.

POJO vPOJO = new POJO();
final POJO.abc in = vPOJO.new abc(); //Notice the final
System.out.println(in.name);
in.name = "World";
System.out.println(in.name);
in = vPOJO.new abc(); // Compilation error
System.out.println(in.name);

And of course, if you want to prevent reassignment of the name field, make the field final instead. If you did that,

in.name = "World";

would no longer compile.

This Wikipedia article describes various uses of final. Summed up, they are:

  • final classes
    • can't be extended
  • final methods
    • can't be overridden
  • final variables/fields
    • can't be reassigned

There is also the issue of static final methods.

Salem
  • 13,516
  • 4
  • 51
  • 70
  • 1
    you are very correct, I got confused between variables and classes... this was so brain freeze of me... – ViS Jul 11 '17 at 11:00
1

The class is final:

final class abc {
    String name="abc";
}

but not the field. And of course that is the same as with "normal" classes - it prevents subclassing that inner class. That is all there is to this!

To prevent re-assining that value; you do what you do for normal classes as well:

class abc {
  final String name="abc";
}

make the field final!

See here for further reading what final is about, depending on the context.

GhostCat
  • 137,827
  • 25
  • 176
  • 248