0

I'm a Java newbie. I want to make some variable read-only in some special scope.how can I do it? Can I add some rules of grammar? Or there are any way work?

sample:

public void func(Object obj); // how can i make variable obj read-only?
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
ZJiaQ
  • 1

5 Answers5

3

Try this:

public void func(final Object obj); 

When a variable is declared with the final keyword, its value can’t be modified. That means a reference variable declared final can never be reassigned to refer to a different object.

The data within the object can be changed. the state of the object can be changed but not the reference.

  • The value can be modified, if the object was an array, you could assign a new value to one of the indexes. The variable obj cannot be reassigned. – matt Aug 09 '20 at 18:54
  • That's correct. To be precise, a reference variable declared final can never be reassigned to refer to a different object. – Łukasz Olszewski Aug 10 '20 at 07:01
1

make the method look like this:
public void func(final Object obj) {...}

inside of the method body you can only read the variable but cannot assign any value to is. so its read-only.
(final means, that you can only assign once an value to an variable
-> final double pi = 3.14159265359d; )

1

Change it to public void func(final Object obj); .

But be cautious, the object itself can still be changed. See this example:

List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);//[1,2,3]
foo(list);
System.out.println(list);//[1,2,3,4], the list was mutated.
....
public void foo(final List<Integer> list){
   list.add(4);
}
JCWasmx86
  • 3,473
  • 2
  • 11
  • 29
1

You can declare a variable as final e.g. final MyClass obj = aVal to prevent assigning something other than the first assignment. However, note that obj can still be modified i.e. obj = someOtherVal is not possible but you can do obj.setX(...) if there is a setter method setX in MyClass.

The only way both re-assignment and modification can be prevented is by defining the class as immutable and then declaring a variable of it with the keyword, final.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

You can pass an object with final keyword to func(Object obj).

Please check below sample example

public class FinalExample {

    public static void main(String[] args) {
    
        FinalExample ex = new  FinalExample();
        
        A a = new A();
        a.setI("Test");
    
        ex.func(a);
        
    }
    
    public void func(final A a) {
        
        System.out.println(a.getI());
    }
    
}


public class A {

    public String i;

    public String getI() {
        return i;
    }

    public void setI(String i) {
        this.i = i;
    }
    
}
Yogesh
  • 126
  • 9