How to call one constructor from another in Java?


You can call one constructor from another using this().

Example

This is a default constructor This is parameterized constructor

Live Demo

public class Sample {
   int num;
   public Sample() {
      System.out.println("This is default constructor");
      num = 30;
   }
   public Sample(int value) {
      this();
      System.out.println("This is parameterized constructor");
      num = value;
   }
   public static void main(String args[]){
      Sample s = new Sample(30);
   }
}

Output

This is default constructor 
This is parameterized constructor

Updated on: 30-Jul-2019

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements