Java program to call one constructor from another
Here's an example Java program to call one constructor from another constructor:
public class Example { private int x; private int y; private String name; public Example(int x, int y, String name) { this.x = x; this.y = y; this.name = name; } public Example(int x, int y) { this(x, y, "default"); } public int getX() { return x; } public int getY() { return y; } public String getName() { return name; } }
This program defines a class called "Example" with two constructors. The first constructor takes three arguments (an int x, an int y, and a String name) and initializes the corresponding instance variables. The second constructor takes two arguments (an int x and an int y) and calls the first constructor with the provided values for x and y and a default value for the name parameter.
The "this" keyword is used to call the first constructor from the second constructor. The "this" keyword refers to the current object (i.e., the object being created by the constructor), and the arguments passed to the "this" keyword are passed on to the first constructor.
Here's an example usage of the Example class:
Example example1 = new Example(10, 20, "example1"); Example example2 = new Example(30, 40); System.out.println(example1.getName()); // Output: example1 System.out.println(example2.getName()); // Output: default
In this example, we create two Example objects using the two constructors. The first Example object is created with x=10, y=20, and name="example1", while the second Example object is created with x=30, y=40, and name="default". The getName() method is used to retrieve the name values of the Example objects, which are printed to the console.