I am getting some “Stack Over Flow” Exception while I am executing below code.
I am making an “Anonymous Inner class”.
public class Prac_RegularInnerClass {
public static void main(String args[])
{
Child1 c1=new Child1();
c1.method4();
}
}
class Parent1{
public int z=10;
public void method1()
{
System.out.println("We are in Method 1!!!!!!!!!\n\n");
}
public void method2()
{
System.out.println("We are in Method 2!!!!!!!!!\n\n\n");
}
}
class Child1 extends Parent1{
//Anonymous Inner class.
Parent1 p1=new Child1(){
public void method1()
{
}
};
public void method4()
{
p1.method1();
p1.method2();
}
}
I have made parent class Parent1. I have made a chile class Child1.
Can anyone explain?
That may be because within Child1 in construction phase you are setting the p1 property as an anonymous subclass of Child1 itself, which makes a new Child1 object instantiate, which makes a new Child1 object instantiate, which makes a new Child1 object instantiate, which makes a new Child1 object instantiate, and so on.
Instead that, either assign new objects after constructing them or assign an object of a different type which doesn’t end in recursion.