相关疑难解决方法(0)

为什么 javac 允许一些不可能的强制转换而不是其他的?

如果我尝试将 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 相同。

java casting compiler-errors javac

53
推荐指数
2
解决办法
2230
查看次数

ClassCastException与"无法强制转换"编译错误

为我的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();我得到一个编译错误的时候了.

两个问题:

  1. 为什么上面的代码完全编译?电话似乎与Roamable无关?
  2. 为什么代码编译new Phone(),但不编译new String()

java inheritance casting classcastexception

14
推荐指数
1
解决办法
4178
查看次数

Java:将类转换为不相关的接口

显然,这会导致编译错误,因为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)

java casting runtime compilation interface

8
推荐指数
1
解决办法
1416
查看次数

Java Customs类实例无法强制转换为String.为什么?

为什么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)

java

5
推荐指数
2
解决办法
86
查看次数

在java中将类转换为接口

为什么界面允许所有类?

例如,我有以下代码:

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,那么上面的代码将成功运行.

有人可以解释为什么界面允许所有类投射?

java

1
推荐指数
1
解决办法
1006
查看次数