Jasnoor Singh Brar Jasnoor Singh Brar - 1 year ago 144
Java Question

StackOverflowError when calling method of subclass object?

Executing the Test class gives a StackOverFlow error :(

Parent class :

package Pack;

public class Alpha {
protected void sayHi() {
System.out.println("Hi...from Alpha");
}
}


Child class :

import Pack.Alpha;

public class AlphaSub extends Alpha {
AlphaSub sb=new AlphaSub() ;

void hi() {
sb.sayHi() ;

}
}


Test class :

public class test {
public static void main(String[] args) {

AlphaSub ob=new AlphaSub() ;
ob.hi() ;
}


}

Answer Source

Your stackoverflow has nothing to do with the inheritance, but with this line (inside AlphaSub):

AlphaSub sb=new AlphaSub() ;

You are creating a new AlphaSub instance inside your AlphaSub, which causes an endleess loop. I assume you don't even make it to the ob.hi() line in your test

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download