Domanda

Consider the following code :

public class TestClass
{
  TestClass()
  {
      super(); 
      System.out.printf("yes it is called");

  }

  public static void main(String[] args)
  {
        new TestClass();
  }

}

Now as anonymous object is created , it calls the constructor. Now with super , it agian calls it self and again the process repeats . This should create infinite recursion.But this is not what happens . Why ?

È stato utile?

Soluzione 2

super() in your case just calls new Object() (all java classes inherit from the Object class), something that would happen anyway. No recursion here

Altri suggerimenti

This is not recursion. In a constructor, calling super(); calls the superclass constructor, not itself.

If you were to say this(); inside that constructor, then the compiler would catch "recursive constructor invocation" as a compiler error.

super() is in reference to the superclass, you are calling Object's constructor.

If you were to make this infinite recursion, you would use this

public class SomeClass {

    public SomeClass() {
        this(); //recursion!
    }

}

Of course, this is a compilation error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top