Why is this Java casting causing an error?

I was wondering why the link "w" after obj = w;throws an error. Aren't you just creating another pointer to this w example by saying obj = w? That is why it is different to say 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 
   }
}
+1
source share
4 answers

There is nothing like quoting JLS in the first place in the morning.

JLS 6.3. Scope of declaration:

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 other declarators to the right of the local variable declaration statement.

and

JLS 14.2. Blocks:

, .

? varialbe w

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

( " " ​​), . ,

System.out.println(w); 

w .

obj?

public static void main(String[] args) {

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

.

System.out.println(obj);

, obj .

+4

.

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

w obly, . ,

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

w , . . , :

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);
      System.out.println(w);
   }
}
0

, . , , . java , , . , - "if" "try", . . . , - -, (), (, ), .

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

Source: https://habr.com/ru/post/1622519/


All Articles