How to call one constructor from another in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 08-Jan-2018 06:27:01
Advertisements