java – 强制转换传递的引用会产生什么作用

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

java - what does casting a passed reference do

问题

我记得阅读过这样一段话:“在Java中将对象传递给方法时,我们将它们作为引用传递,但是在方法中为引用分配新值不会更改对象,因为引用按值传递,该值仅被新值替换”;

但是,如果我们在赋值以外做其他操作,例如:

//Main.java
public class Main {
    public static void main(String[] args) {
        Object A = new String("newString");
        mUtil mutil = new mUtil();
        System.out.println(A.toString());
        mutil.someMethod(A);
        A = new Object(); //这里会抛出异常吗?因为 A 已经被强制转换为 String 类型
        
    }
}

//mUtil.java
public class mUtil {
    mUtil() {} //无参构造函数

    public void someMethod(Object a) {
        a = (String) a;
        System.out.println("来自 someMethod: " + a.toString());
    }
}

正如我已经注释的那样,这行代码会抛出异常吗?

英文:

I remember reading "when we pass object to methods in java we pass them as reference but assigning a new value to the reference in method doesn't change the object because the references are passed by value and the value is simply replaced by the new one"

But, what if we're doing something else besides assignment, for example:

//Main.java
public class Main{  
  public static void main(String[] args){
    Object A = new String("newString");
    mUtil mutil = new mUtil();
    System.out.println(A.toString());
    mutil.someMethod(A);
    A = new Object(); //shouldn't this throw an exception because the A has been cast to a String
    
  }
}

//mUtil.java
public class mUtil{
  mUtil(){} //no-args constructor
public void someMethod(Object a){
      a = (String)a;
      System.out.println("From someMethod: "+a.toString());
  }
}  

As I've commented, shouldn't that line throw an exception?

答案1

得分: 1

强制转换 a 不会改变 a,它只是向代码显示 a 应该被解释为什么类型(这里是字符串)。

英文:

Casting a does not change a, it merely shows the code afterwards what a should be interpreted as (here: String).

huangapple
  • 本文由 发表于 2020年4月6日 19:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61059000.html
匿名

发表评论

匿名网友

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

确定