satheesh
satheesh

Reputation: 1451

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?

Upvotes: 4

Views: 368

Answers (4)

Umesh Kacha
Umesh Kacha

Reputation: 13686

Stackoverflow error will occur whenever you try to create instance of same class as a member variable. So h instance is created infinite times and hence stackoverflow error came.

For e.g. the code you gave, even without inner class it will throw stackoverflow error

public class maininherit {

maininherit h=new maininherit();


public static void main(String[] args){
   maininherit t=new maininherit();
   t.mai();
 }

public void mai(){
    System.out.print("hellllll");
    h.mai();
}}

Avoid creating object of the class itself as a member or field

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299148

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

Upvotes: 1

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95629

The issue here is not with your main and mai functions, but with your initialization of the maininherit h member variable. The problem is that each instance of maininherit is creating a maininherit object (which in turn, creates a maininherit object, etc.). Marking that as a static member will cause a single copy to be shared by all instances, which will solve this issue.

Upvotes: 1

Koziołek
Koziołek

Reputation: 2874

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.

Upvotes: 9

Related Questions