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?
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?
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.
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; )
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);
}
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
.
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;
}
}