0

My code is very simple, and I'm trying to learn java/android studio, I can't figure out why am I getting a stackoverflow with this:

public class Main {

    private String main_name = "dummy_string";
    private String name1 = "name1";
    private String name2 = "name2";
    private String name3 = "name3";

    private final Main[] Drinks={
        new Main(name1),
        new Main(name2),
        new Main(name3)
    };

    public Main(){}

    private Main(String name_value){
        this.main_name = name_value;
    }

    public  void get_value(int index){
        System.out.println(this.Drinks[index]);
    }

    public static void main(String[] args) {
        Main main_obj = new Main();
        main_obj.get_value(0);
        main_obj.get_value(1);
        main_obj.get_value(2);
   }  
}

Even though I have made no recursive calls, stackoverflow is occuring.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
juztcode
  • 1,196
  • 2
  • 21
  • 46
  • 1
    `Drinks` array is the problem. When you create `Main` object you create also an array which has 3 `Main` objects and so on recursively... – Michał Krzywański Aug 28 '19 at 16:23
  • 4
    You have made recursive calls: when you construct a Main, it creates an array populated with 3 new Main instances, so the Main constructor is called 3 additional times, which constructs 9 more Main instances, etc. etc. – JB Nizet Aug 28 '19 at 16:25
  • 3
    Side note: variables and mathods start with a lwoercase letter, and are camelCased. They never contain an underscore. – JB Nizet Aug 28 '19 at 16:26
  • but, that's really a convention, isn't it? I like underscores so I kept them,.... does it cause any problem down the road? – juztcode Aug 28 '19 at 16:41
  • If you share stacktrace, you will see recursion in [ method](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.9) – rkosegi Aug 28 '19 at 16:41

1 Answers1

8

There is your problem:

private final Main[] Drinks={
    new Main(name1),
    new Main(name2),
    new Main(name3)
};

You're creating Main class with Drinks array in it, that contains instances of Main each of which must have Drinks array and so on.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • but, isn't instantiating a class inside the same class allowed in java? – juztcode Aug 28 '19 at 17:12
  • 1
    @juztcode It does allow but in doing so will result in your program going into a recursive death spiral. For more check this out https://stackoverflow.com/questions/13607757/object-of-the-class-as-instance-variable-inside-the-class?lq=1#answer-13608203 – Yoshikage Kira Aug 28 '19 at 17:34