final keyword error Java

In Java, we use the final keyword with variables to indicate that their values should not be modified. But, I see that you may edit the value in the constructor / methods. If the variable is static, this is another compilation fault.

The code is as follows:
Code:
import java.util.ArrayList;
import java.util.List;

class Test {
  private final List foo;

  public Test()
  {
      foo = new ArrayList();
      foo.add("foo"); // Modification-2
  }
  public static void main(String[] args)
  {
      Test t = new Test();
      t.foo.add("bar"); // Modification-3
      System.out.println("print - " + t.foo);
  }
}

The code above is error-free.

Now make the variable static:

Code:
private static final List foo;

It is now a compilation error. How does this final work in practise?
 
Make sure that you don't access to private attributes outside the actual class, add a getter and a setter.
Also define a type for you collections, you don't want the runtime to assign any type it wants.

Code:
import java.util.ArrayList;
import java.util.List;

public class Test {
    private final List<String> fooList;

    public void addFoo(String foo) {
        this.fooList.add(foo);   
    }

    public List<String> getFoo() {
        return fooList;
    }

    public Test() {
        fooList = new ArrayList<String>();
    }
}
 
I implemented immutability of my objects by using mprotect to mark the section of ram the buffer contents are stored in as read only . This only works for objects backed by native memory
 
Make sure that you don't access to private attributes outside the actual class, add a getter and a setter.
Also define a type for you collections, you don't want the runtime to assign any type it wants.

Code:
import java.util.ArrayList;
import java.util.List;

public class Test {
    private final List<String> fooList;

    public void addFoo(String foo) {
        this.fooList.add(foo);  
    }

    public List<String> getFoo() {
        return fooList;
    }

    public Test() {
        fooList = new ArrayList<String>();
    }
}

Thanks it helped me
 
Got it
You could patch the jvm to do it using the same way swap files and memory mapped files are done .. mprotect violation signals a handler to fetch the segment and then return the execution flow to the point the segmentation violation was triggered
 
Back
Top