Java 处理 class 类型参数的方式
我正在查看 Walter Savitch 书中的示例“Java 简介”
// This method does not do what we want it to do.
public static void openFile(String fileName,
PrintWriter stream) throws FileNotFoundException
{
stream = new PrintWriter(fileName);
}
PrintWriter toFile = null;
try
{
openFile("data.txt", toFile);
}
作者给出的解释,这没有任何意义,至于为什么在 try
之后 toFile = null
谢谢!
I am looking at example in the example in Walter Savitch book "Java Introduction"
// This method does not do what we want it to do.
public static void openFile(String fileName,
PrintWriter stream) throws FileNotFoundException
{
stream = new PrintWriter(fileName);
}
PrintWriter toFile = null;
try
{
openFile("data.txt", toFile);
}
Author gives explanation, which does not make any sense, as to why toFile = null
after try
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要更深入地阅读本书的该部分。 (我确信它确实有意义......但你只是还没有理解它。)
很明显,作者实际上是在试图说明 Java 的一个非常重要的方面......参数是如何传递的。
具体来说,他试图说明两个
stream
标识符用于不同变量,并且方法内的赋值不会影响
stream
在try
之前声明的变量。分配给方法内stream
变量的值会丢失。这说明Java使用“按值传递”作为其参数传递机制。 (如果您需要从方法调用中获取值,最简单的方法就是
返回
它。)You need to read that section of the book more deeply. (I'm sure that it actually DOES make sense ... but you just haven't understood it yet.)
It is clear that the author is actually trying to illustrate an very important aspect of Java ... how parameters are passed.
Specifically, he is trying to illustrate that the two
stream
identifiers are for different variables, and that the assignment inside the methoddoes NOT effect the
stream
variable declared just before thetry
. The value that is assigned to thestream
variable inside the method gets lost.This illustrates that Java uses "pass by value" as its parameter passing mechanism. (If you need to get a value back from a method call, the simple way to do it is to
return
it.)作者试图向您解释,更改方法内部变量所指的内容在方法外部是不可见的。
调用
openFile()
后,toFile
将为null
,因为引用值已传递给该方法并分配给本地流变量。除非显式返回,否则在方法外部无法看到对方法内部
stream
值的更改。openFile()
需要返回新的PrintWriter
:并被调用为:
The author is trying to explain to you that changing what a variable refers to inside a method isn't visible outside the method.
toFile
will benull
after the call toopenFile()
because the reference value is passed to the method and assigned to the localstream
variable. Changing the value ofstream
inside the method can't be seen outside the method unless you explicitly return it.openFile()
would need to return the newPrintWriter
:and be called as: