为什么这个Java投射会抛出一个错误? [英] Why does this Java casting throw an error?

查看:118
本文介绍了为什么这个Java投射会抛出一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在 obj = w; 之后引用w会抛出一个错误。不是你只是通过说obj = w创建另一个指针指向这个w实例?也就是说为什么说不同于 String s =hi; String w = s; 谢谢!

I was wondering why referencing "w" after obj = w; will throw an error. Aren't you just creating another pointer to that w instance by saying obj = w? I.e. why is it different to saying something like String s = "hi"; String w = s; Thank you!

public class Casting {
   public static void main(String[] args) {
      // casting doesn't change the object
      Object obj;
      { 
          Stopwatch w = new Stopwatch();
          obj = w;
      }
      System.out.println(obj); // this line does work
      System.out.println(w); //this line does not work 
   }
}


推荐答案

早上没有引用JLS的第一件事。

There's nothing like quoting the JLS first thing in the morning.


JLS 6.3。声明范围:

JLS 6.3. Scope of a Declaration:


块中的局部变量声明的范围(§14.4)是块的其余部分,声明出现,从它自己的初始化器开始,并包括在局部变量声明语句中右边的任何进一步的声明器。

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.



JLS 14.2。块:

JLS 14.2. Blocks:


是大括号中的一系列语句,本地类声明和局部变量声明语句。

A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.


在您的情况下是什么意思?在区块中声明局部varialbe w

What does it mean in your case? The local varialbe w is declared in the block

{ 
    Stopwatch w = new Stopwatch();
    obj = w;
}

(自己的初始化器是块中的第一行)它的范围是那个块的其余部分。对它的引用,

("its own initializer" is the first line in the block) and so its scope is the rest of that that block. The reference to it,

System.out.println(w); 

不在块中,因此 w

那么局部变量 obj 会怎么样呢?它已在块中声明

What about the local variable obj then? It was declared in the block

public static void main(String[] args) {

    Object obj;
    { 
        Stopwatch w = new Stopwatch();
        obj = w;
    }
    System.out.println(obj);
    System.out.println(w);
}

在这种情况下是一个方法块。调用

which in this case is a method block. The call

System.out.println(obj);

位于块内,因此 obj 成功引用。

is inside the block, so obj can be referenced successfully.

这篇关于为什么这个Java投射会抛出一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆