【问题标题】:Why does the compiler not give an error when making a "bad" cast?为什么编译器在进行“坏”转换时不给出错误?
【发布时间】:2013-02-03 14:06:46
【问题描述】:

考虑以下 Java 类:

public class Animal {
    public static void printText(Object obj) {
        System.out.println(obj.toString());
    }
}

class Tiger extends Animal {
    // Contains some unimportant methods.
}

现在,当在 main 方法中键入以下内容时,编译器不会给出任何错误,即使该转换会导致错误。为什么?

public static void main(String[] args) {
    Animal animal = new Animal();
    ((Tiger)animal).printText(animal);  // <= ?? no error in the compiler ??
}

【问题讨论】:

  • 抛出异常。打印编译器错误。不要迷惑​​自己。

标签: java compiler-construction compiler-errors


【解决方案1】:

在您的示例中,很容易知道演员阵容是错误的 - 但在一般情况下并非如此。

如果你有一个方法 Animal getRandomAnimal() 也可能返回 Tiger 会怎样。 (或者更常见的情况,方法 Animal getAnimal() 可能会被子类覆盖以返回 Tiger)。

在编译时,你不可能知道

Tiger tiger = (Tiger)getRandomAnimal();

是否有效,只有在运行时才知道。

【讨论】:

    【解决方案2】:

    因为一般情况下,这在编译时无法检测到。例如:

    Animal a = (someCondition) ? new Animal() : new Tiger();
    
    ((Tiger)animal).printText(animal);
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多