Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting StackOverFlowError in Java

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 StackOverflowErrors 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?

like image 484
satheesh Avatar asked Dec 22 '22 17:12

satheesh


2 Answers

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.

like image 64
Koziołek Avatar answered Jan 04 '23 19:01

Koziołek


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

like image 31
Sean Patrick Floyd Avatar answered Jan 04 '23 21:01

Sean Patrick Floyd