Java Program to Call One Constructor from another

JavaObject Oriented ProgrammingProgramming

<p>In this article, we will understand how to call one constructor from another. The keyword &#39;this()&#39; is used to invoke a constructor.</p><p>Below is a demonstration of the same. We will displaying sum and product of two numbers while using this() &minus;</p><p><strong>Input</strong></p><p>Suppose our input is &minus;</p><pre class="result notranslate">The numbers are defined as 12 and 30</pre><p><strong>Output</strong></p><p>The desired output would be &minus;</p><pre class="result notranslate">The sum is: 42 The product is: 360</pre><h2>Algorithm</h2><pre class="result notranslate">Step 1 - START Step 2 - Declare an integer value namely my_sum Step 3 -&nbsp;In the main class, we define a &lsquo;this&rsquo; reference to the numbers which would be used as input. Step 4 - This will call the &lsquo;this&rsquo; constructor that invokes the current class constructor. Step 5 - Another &lsquo;display&rsquo; function is used to display the sum. Step 6 - An object of the class is created, and the functions are invoked to display the result</pre><h2>Example 1</h2><p>Here, the sum of two numbers is being computed.</p><pre class="demo-code notranslate language-java" data-lang="java">public class Main { int my_sum; Main() { this(12, 30); } Main(int my_input_1, int my_input_2) { System.out.println(&quot;The numbers are defined as &quot; +my_input_1 +&quot; and &quot; +my_input_2); this.my_sum = my_input_1 + my_input_2; } void display() { System.out.println(&quot;The sum is: &quot; + my_sum); } public static void main(String[] args) { Main my_object = new Main(); my_object.display(); } }</pre><h2>Output</h2><pre class="result notranslate">The numbers are defined as 12 and 30 The sum is: 42</pre><h2>Example 2</h2><p>Here, the product of two numbers is being computed.</p><pre class="demo-code notranslate language-java" data-lang="java">public class Main { &nbsp; int my_product; Main() { this(12, 30); } Main(int my_input_1, int my_input_2) { System.out.println(&quot;The numbers are defined as &quot; +my_input_1 +&quot; and &quot; +my_input_2); this.my_product = my_input_1 * my_input_2; } void display() { System.out.println(&quot;The product of the two values is: &quot; + my_product); } public static void main(String[] args) { Main my_object = new Main(); my_object.display(); } }</pre><h2>Output</h2><pre class="result notranslate">The numbers are defined as 12 and 30 The product of the two values is: 360</pre>
raja
Updated on 22-Feb-2022 10:00:43

Advertisements