I was wondering if there was an equivalent to c++'s const in Java. I understand the final keyword, but unfortunately I cannot use that to declare a functions return value final. Instead, it always ensures the function cannot be overridden, correct?
Basically, I want to make sure a given returned class cannot be modified and is read only. Is that possible in Java?
解决方案
Basically, I want to make sure a given returned class cannot be
modified and is read only. Is that possible in Java?
Not directly, but one workaround is an immutable object.
Example -
public final Foo{
private final String s;
public Foo(String s){
this.s = s;
}
// Only provide an accessor!
public String getString(){
return s;
}
}