This is program I am writing. I am getting a StackOverFlowError
exception when I run it:
public class maininherit {
maininherit h = new maininherit() {
@Override
public void mai() {
System.out.print("inner");
}
};
public static void main(String[] args){
maininherit t=new maininherit();
t.mai();
}
public void mai(){
System.out.print("hellllll");
h.mai();
}
}
Here I am getting StackOverflowError
s only when I am using maininherit
class as a reference in the inner class. If I am using other classes I am not getting that error. Can anyone clarify this to me?
Sorry i am thank full for your answers but i had a doubt i don't know whether reasonable or not only repetition of initializations can be possible only when i created instance in constructor of that same class know.then how it is possible to have multiple initializations?
Implementation of your inner class is just override part of maininherit class. So... You init class maininherit then variable h were initialized. New operator were called and then... inner class init maininherit again and need to set h variable.
Your code is infinitive loop of initializations h variable.
This line:
maininherit t=new maininherit();
Creates a new maininherit object (I'll call it m0
), which has a field of the same type (I'll call that m1
)
When m0 is created, m1 is initialized. m1 also has a field, so m2 is initialized. m2 also has a field so m3 is initialized etc.
This would go on forever if the StackOverflowError
didn't oocur
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With