可以在Java中调用final对象吗?

huangapple go评论64阅读模式
英文:

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&lt;String,String&gt; desc = new HashMap&lt;String,String&gt;();
    }

    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&lt;String,String&gt; desc = new HashMap&lt;String,String&gt;();
    call(desc);
  }

  public void call(Map&lt;String, String&gt; desc) {
    // do something, may be desc.put(key, val);
  }
}

huangapple
  • 本文由 发表于 2020年3月17日 03:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/60712182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定