Stackoverflow error

浪尽此生 提交于 2019-12-02 07:59:01

问题


The code given below shows a Stackoverflow error when run.But if I make another class CarChange to create objects of Car ,it runs sucessfully. I am a beginner ,doing this code to understand the importance of upcasting in 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();

回答1:


A stackoverflow usually means you have an infinite loop.

The reason you're receiving this is because you're calling drive from the testdrive method and in that method you're calling drive again.




回答2:


Car() {
    c[0] = new Polo();
    i=0;
}

As Polo is a subclass of Car() - it must be to fit in the Car[] - it will call the Car's constructor when being constructed itself. The Car constructor tries to create a new Polo().

As Polo is a subclass of Car() - it must be to fit in the Car[] - it will call the Car's constructor when being constructed itself. The Car constructor tries to create a new Polo().

As Polo is a subclass of Car() - it must be to fit in the Car[] - it will call the Car's constructor when being constructed itself. The Car constructor tries to create a new Polo().

... you get the picture?




回答3:


It sounds like you might have some infinite recursion happening.

drive() calls testdrive() which class drive() which calls testdriver()...forever, or until you run out of memory, hence your stack overflow error.



来源:https://stackoverflow.com/questions/9124733/stackoverflow-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!