Search code examples
javastack-overflow

Stackoverflow error


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();

Solution

  • 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.