下面给出的代码在运行时显示 Stackoverflow 错误。但是如果我创建另一个类 CarChange 来创建 Car 的对象,它会成功运行。我是初学者,通过编写这段代码来了解 java 中向上转换的重要性。
public class Car {
int i;
Car[] c=new Car[2];
Car() {
c[0] = new Polo();
i=0;
}
void drive(){
c[i].testdrive(); //the overloaded method in subclasses polo and swift
}
void change() {
if(i==0) {
i++;
c[i] = new Swift();
}
}
public void testdrive() {
//overloaded method in subclasses polo and swift
System.out.println(" test drive car");
}
//class Tester {
//main
Car c= new Car();
c.drive();
c.change();
c.drive();
最佳答案
Car() {
c[0] = new Polo();
i=0;
}
因为 Polo 是 Car() 的子类 - 它必须适合 Car[] - 它会调用 Car自己构造时的构造函数。 Car 构造函数尝试创建一个新的 Polo()。
因为 Polo 是 Car() 的子类 - 它必须适合 Car[] - 它会调用 Car自己构造时的构造函数。 Car 构造函数尝试创建一个新的 Polo()。
因为 Polo 是 Car() 的子类 - 它必须适合 Car[] - 它会调用 Car自己构造时的构造函数。 Car 构造函数尝试创建一个新的 Polo()。
...你明白了吗?
关于java - 计算器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9124733/