如果我尝试将 a 转换String为 a java.util.Date,Java 编译器会捕获错误。那么为什么编译器不将以下内容标记为错误呢?
List<String> strList = new ArrayList<>();
Date d = (Date) strList;
Run Code Online (Sandbox Code Playgroud)
当然,JVMClassCastException在运行时抛出 a ,但编译器不会标记它。
行为与 javac 1.8.0_212 和 11.0.2 相同。
为我的OCA Java SE 7程序员学习考试,所以新手问题.我有一个我不明白的例子问题.以下代码编译,但在运行时给出ClassCastException:
interface Roamable {
}
class Phone {
}
public class Tablet extends Phone implements Roamable {
public static void main(String... args) {
Roamable var = (Roamable) new Phone();
}
}
Run Code Online (Sandbox Code Playgroud)
当我改变Roamable var = (Roamable) new Phone();成Roamable var = (Roamable) new String();我得到一个编译错误的时候了.
两个问题:
new Phone(),但不编译new String()?显然,这会导致编译错误,因为Chair与Cat无关:
class Chair {}
class Cat {}
class Test {
public static void main(String[] args) {
Chair chair = new Char(); Cat cat = new Cat();
chair = (Chair)cat; //compile error
}
}
Run Code Online (Sandbox Code Playgroud)
那么为什么我在运行时只将Cat引用转换为不相关的接口Furniture时才会出现异常,而编译器显然可以告诉Cat不实现Furniture?
interface Furniture {}
class Test {
public static void main(String[] args) {
Furniture f; Cat cat = new Cat();
f = (Furniture)cat; //runtime error
}
}
Run Code Online (Sandbox Code Playgroud) 为什么A的实例可以转换为List而不能转换为String?
class A{}
...
A a = new A();
List list = (List)a; //pass
String s = (String)a; //compile error
Run Code Online (Sandbox Code Playgroud) 为什么界面允许所有类?
例如,我有以下代码:
interface I1 { }
class C1 { }
public class Test{
public static void main(String args[]){
C1 o1 = new C1();
I1 x = (I1)o1; //compiler compile its successfully but failed in run time
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么它在运行时失败,因为C1类没有实现I1接口.如果C1类实现I1,那么上面的代码将成功运行.
有人可以解释为什么界面允许所有类投射?