calling a java constructor of same class from non static context leads to recursion but with static it works fine?

Mayank Madhav

I am trying to understand initialization order of Java class. Specifically when and in what order are static and Instance initializer/fields are executed. I came up with example as in this stackoverflow Question. Why does adding static to the self constructor invocation stop the code from going into recursion.

public class Test {
    public static void main(String a[]) {
        Cons1 c1 = new Cons1();
    }
}

class Cons1 {
    static Cons1 c = new Cons1(); /* if static is removed then recursion 
                                    occurs */
    Cons1() {
         //does something
    }
}

Is there any specific reason for this difference in behavior between static and instance context. I went through the Java doc Detailed Initialization Procedure, but unable to understand what is the logic behind such behavior. Any explanation or reference to JLS specs will be helpful.

PS : I have gone through this Similar stackoverflow post, However I cannot get my answer from there.

Andrew Tobilko

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

JLS 10 - 8.3.1.1. static Fields

On the other hand,

If the declarator is for an instance variable (that is, a field that is not static), then the following rules apply to its initializer:

  • At runtime, the initializer is evaluated and the assignment performed each time an instance of the class is created.

JLS 10 - 8.3.2. Field Initialization


Let's add a println statement to see the whole picture:

class Cons1 {
    static Cons1 c = new Cons1();

    Cons1() {
        System.out.println("the constructor was called");
    }

    public static void main(String[] args) {
        Cons1 c1 = new Cons1();
        Cons1 c2 = new Cons1();
    }
}

It outputs "the constructor was called" three times:

1 - when the class was loaded and the static field c got initialised;
2 - when c1 was created;
3 - when c2 was created.

Now we will compare that with the example with an instance field:

class Cons1 {
    Cons1 c = new Cons1();

    Cons1() {
        System.out.println("the constructor was called");
    }

    public static void main(String[] args) {
        Cons1 c1 = new Cons1();
    }
}

Obviously, it fails with the next stacktrace printing nothing:

Exception in thread "main" java.lang.StackOverflowError
    at Cons1.<init>(Cons1.java:33)
    ...
    at Cons1.<init>(Cons1.java:33)

The reason is that each instance of Cons1 requires another Cons1 object. So we overflow the call stack pushing Cons1.<init> methods in it. As a result, we end up with the exception when the stack reaches its max-allowed size.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Calling a non static method from a in a static context

From Dev

Calling a static method from a non-static context

From Java

non-static class cannot be referenced from a static context

From Dev

Calling ES6 class constructor from class static method

From Dev

java: non-static variable this cannot be referenced from a static context

From Dev

Non static variable cannot be referenced from static context java

From Dev

non-static variable cannot be referenced from static context [JAVA]

From Dev

Java non-static method cannot be refenced from a static context

From Dev

non-static variable cannot be referenced from a static context java

From Java

Static and non-static method in one class with the same name JAVA

From Dev

Java static and non-static variables in the same class

From Dev

Instantiation of a Non-static Class(context) in a Static method with a Constructor taking type Object as parameter

From Java

Constructor is static or non static

From Dev

Non-Static variable while calling a constructor

From Java

Why does String::isEmpty works when non-static method cannot be referenced from a static context?

From Dev

Calling a non-static method from outside the class

From Dev

Trouble calling a non-static method from an abstract class

From Dev

Calling non-static method from another file/class

From Dev

referencing the App context from a non-static inner class

From Dev

Calling constructor of inherited class with only static methods

From Java

Java: How to get a class object of the current class from a static context?

From Dev

Non-Static method from a static context [Comparing two sets of class instances]

From Dev

Calling a non-static function of a UIViewController class

From Dev

What's the function of a static constructor in a non static class?

From Dev

Why the compiler allow to create an object of non static class in static context?

From

How to call non-static method from static method of same class?

From Java

java - Non-static method 'getLogger' cannot be referenced from a static context

From Java

Java Generics: non-static type variable T cannot be referenced from a static context

From Java

Non-static method cannot be referenced from a static context in java 8 streams

Related Related

  1. 1

    Calling a non static method from a in a static context

  2. 2

    Calling a static method from a non-static context

  3. 3

    non-static class cannot be referenced from a static context

  4. 4

    Calling ES6 class constructor from class static method

  5. 5

    java: non-static variable this cannot be referenced from a static context

  6. 6

    Non static variable cannot be referenced from static context java

  7. 7

    non-static variable cannot be referenced from static context [JAVA]

  8. 8

    Java non-static method cannot be refenced from a static context

  9. 9

    non-static variable cannot be referenced from a static context java

  10. 10

    Static and non-static method in one class with the same name JAVA

  11. 11

    Java static and non-static variables in the same class

  12. 12

    Instantiation of a Non-static Class(context) in a Static method with a Constructor taking type Object as parameter

  13. 13

    Constructor is static or non static

  14. 14

    Non-Static variable while calling a constructor

  15. 15

    Why does String::isEmpty works when non-static method cannot be referenced from a static context?

  16. 16

    Calling a non-static method from outside the class

  17. 17

    Trouble calling a non-static method from an abstract class

  18. 18

    Calling non-static method from another file/class

  19. 19

    referencing the App context from a non-static inner class

  20. 20

    Calling constructor of inherited class with only static methods

  21. 21

    Java: How to get a class object of the current class from a static context?

  22. 22

    Non-Static method from a static context [Comparing two sets of class instances]

  23. 23

    Calling a non-static function of a UIViewController class

  24. 24

    What's the function of a static constructor in a non static class?

  25. 25

    Why the compiler allow to create an object of non static class in static context?

  26. 26

    How to call non-static method from static method of same class?

  27. 27

    java - Non-static method 'getLogger' cannot be referenced from a static context

  28. 28

    Java Generics: non-static type variable T cannot be referenced from a static context

  29. 29

    Non-static method cannot be referenced from a static context in java 8 streams

HotTag

Archive