문제

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 ?

도움이 되었습니까?

해결책 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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top