Calling One Constructor from Another


This example calls one constructor from another constructor in Java. There are two constructors inside the Two class. Inside the first constructor, we have used this keyword to call the second constructor. The second constructor is called from the first constructor by passing arguments.

Note that the line inside a constructor that calls another constructor should be the first line of the constructor; i.e., this(a,b) should be the first line of Two().

Two.java (calling one constructor from another)

 // Java program to call one constructor from another
 public class Two {
   int sum; 
   // Can’t be accessed by static methods without being declared static.
   static int a, b;

   // The driver method
   public static void main( String[ ] args ) {
     a = Integer.parseInt( args[0] );
     b = Integer.parseInt( args[1] );
     // Call the first constructor.
     Two obj = new Two( );
     // Call the display method.
     obj.display( );
   }
   // First constructor
   Two( ) {
     // Calling the second constructor
     ( a, b );
   }
   // Second constructor
   Two( int arg1, int arg2 ) {
     // Add two value.
     .sum = arg1 + arg2;
   }
   // A method to print the sum
   void display( ) {
     System.out.println( "Sum is: " + sum );
   }
 }
shell> java Two            

Also, we cannot directly access the instance variables within a static method because a static method can only access static variables or static methods. An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn’t make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.




      Undertaking a Masters program ensures that you always    
      have a lot on your plate (are too busy).