Why does this code snippet not have runtime errors as described in the Java tutorials documentation?
•
Java
public class @R_150_2419@ {
public class @R_150_2419@ { private Object object; public void set(Object object) { this.object = object; } public Object get() { return object; } }
Referring to the official Java Tutorial documentation and this article in the above code snippet, I try to reproduce runtime errors What's wrong with my code because it doesn't produce any runtime errors?
I wrote the code
public class @R_150_2419@ { private Object obj; public void set(Object obj) { this.obj = obj; } public Object get() { return obj; } public static void main(String [] args) { @R_150_2419@ g = new @R_150_2419@(); System.out.println(g.get()); g.set("hello again"); System.out.println(g.get()); } }
Solution
public static void main(String[] args) {
public static void main(String[] args) { @R_150_2419@ g = new @R_150_2419@(); g.set("hello again"); Integer i = (Integer) g.get(); System.out.println(i + 1); }
This code passes in a string, but attempts to retrieve integer The compiler cannot detect this and will fail At runtime, it throws ClassCastException
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码