相关疑难解决方法(0)

Java转换导致运行时错误而不是编译错误

以下代码段将导致运行时:

class Vehicle {
    public void printSound() {
        System.out.print("vehicle");
    }
}

class Car extends Vehicle {
    public void printSound() {
        System.out.print("car");
    }
}

class Bike extends Vehicle {
    public void printSound() {
        System.out.print("bike");
    }
}

public class Test {
    public static void main(String[] args) {
        Vehicle v = new Car();
        Bike b = (Bike) v;

        v.printSound();
        b.printSound();
    }   
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么会导致运行时错误而不是编译错误?难道编译器不应该知道'v'已经是'Car'并且不能被投入'Bike'吗?

java

4
推荐指数
2
解决办法
8301
查看次数

为什么有可能新建一个接口数组

为什么Java中可以使用以下内容?

Integer[] ints = (Integer[])new Comparable[10];
Run Code Online (Sandbox Code Playgroud)

但它ClassCastException在运行时获得.new接口数组的用例是什么?

java arrays casting interface

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

标签 统计

java ×2

arrays ×1

casting ×1

interface ×1