0

I don't Understand why Default constructor is executed after parameterized constructor in this program ?

class A{
  int a , b;

  A(){
    this(10,20);
    System.out.println("Inside Default Constructor values:"+a+" "+b);
  }

  A(int a , int b){
    this.a=a;
    this.b=b;
    System.out.println("Inside Parameterized Constructor values:"+a+" "+b);
  }
}

public class thisExample {
  public static void main(String[] args) {
    A obj = new A();
  }
}

This gives output as :

Inside Parameterized Constructor values:10 20
Inside Default Constructor values:10 20
Alfabravo
  • 7,493
  • 6
  • 46
  • 82
Balaji
  • 73
  • 1
  • 6

2 Answers2

2

Its clear from your code why its happening

A obj = new A();

calls your default constructor

A(){
    this(10,20);
    System.out.println("Inside Default Constructor values:"+a+" "+b);
}

which further calls yours parametrized constructor first this(10,20); so your code prints Inside Parameterized Constructor values:10 20 first and than it prints Inside Default Constructor values:10 20

Aditi Singh
  • 117
  • 1
  • 8
1

The first statement in the default constructor executes the parameterized constructor. You can include the sysout before executing the this(10, 20) and check the behavior.

notionquest
  • 37,595
  • 6
  • 111
  • 105