-6

I am really confused about the outcome of the following program. Could anyone explain it?

public class Prg {
    Prg () {
        this(0);
        System.out.println("Hi ");
    }

    Prg (int x) {
        this(0, 0);
        System.out.println("Hello");
    }

    Prg (int x, int y) {
        System.out.println("How are you");
    }

    public static void main(String[] args) {
        Prg ob = new Prg ();
    }
}

Output:

How are you
Hello
Hi

Azodious
  • 13,563
  • 1
  • 33
  • 68
geetha
  • 69
  • 1
  • 5

1 Answers1

1

this(0); is an example of constructor delegation. Here you're calling, from a constructor, the constructor that takes an pair of ints as an argument. To exploit this idiom, the call to another constructor must be the first statement of the calling constructor.

The rest of the behaviour is adequately explained with a line by line debugger.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470