英文:
Is it possible to call a final object in Java?
问题
可以在同一个类的另一个方法中调用在方法中声明的 final 对象吗?
public class MyClass{
public void description(){
//一些代码...
//一些代码..
final HashMap<String,String> desc = new HashMap<String,String>();
}
public void call(){
// 在这里可以调用对象 desc
}
}
英文:
Is it possible to call a final object which is declared in a method, in another method of the same class?
public class MyClass{
public void description(){
//something...
//something..
final HashMap<String,String> desc = new HashMap<String,String>();
}
public void call(){
}
}
Can I call the object desc
in function call()
?
答案1
得分: 1
在Java中并不存在final object
这样的概念。你声明的是一个final变量,或者是一个final引用。这意味着你不能在作用域内重新分配该变量名。然而,这并不影响所引用的对象本身。因此,你可以按以下方式传递这个对象:
public class MyClass {
public void description() {
//一些操作...
//一些操作..
final HashMap<String, String> desc = new HashMap<String, String>();
call(desc);
}
public void call(Map<String, String> desc) {
//做一些操作,可能是desc.put(key, val);
}
}
英文:
There's no such thing as final object
in java. What you declared is a final variable, or final reference. It means you cannot reassign this variable name within the scope. This says nothing about the object being referenced however. So you can pass this object as follows:
public class MyClass {
public void description() {
//something...
//something..
final HashMap<String,String> desc = new HashMap<String,String>();
call(desc);
}
public void call(Map<String, String> desc) {
// do something, may be desc.put(key, val);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论