Java Constructors Overloading in Java
In Java, constructors can be overloaded just like methods. This means that you can define multiple constructors in a class with different parameter lists, which allows you to create objects with different initial values or behaviors depending on the constructor used.
Here's an example of constructor overloading in Java:
erfer to:theitroad.compublic class MyClass { private int value; public MyClass() { this.value = 0; } public MyClass(int value) { this.value = value; } public MyClass(String value) { this.value = Integer.parseInt(value); } public int getValue() { return value; } }
In this example, we have a class called MyClass
with a single field value
, and three constructors that initialize the value
field with an integer value, a string value, or the default value of 0. The first constructor takes no arguments and initializes the value
field to 0, the second constructor takes an integer argument and sets the value
field to the value passed as an argument, and the third constructor takes a string argument, parses it as an integer, and sets the value
field to the parsed value.
To create an object of MyClass
using a specific constructor, we can use the following code:
MyClass obj1 = new MyClass(); // uses the no-argument constructor MyClass obj2 = new MyClass(10); // uses the integer argument constructor MyClass obj3 = new MyClass("20"); // uses the string argument constructor
This will create three objects of MyClass
, with different values for the value
field.