A constructor in Java is a special method that is used to initialize an object. It is called when an object of a class is created. It is a block of code that is called when an instance of an object is created, and memory is allocated for the object.
It always has the same name as the class and does not have a return type (not even void).
Here is an example of a constructor in a class:
public class MyClass { int x; // Constructor for MyClass public MyClass() { x = 5; // Initialize the variable x with the value 5 } }
In this example, MyClass
is a constructor that is used to initialize the x
variable to 5 when we create objects of the MyClass
class.
You can also have constructors with parameters. For example:
public class MyClass { int x; // Constructor for MyClass public MyClass(int val) { x = val; // Initialize the variable x with the passed value } }
In this case, when you create a new object, you would pass in the value that you want x
to be initialized to, like so:
MyClass myObj = new MyClass(10); // x in myObj is now 10
There are two types of constructors in Java:
Default constructor: If you do not define a constructor in the class, compiler will create a default constructor in the class that initializes all instance variables with default values (null for objects, false for boolean, 0 for numeric values).
Parameterized constructor: It's a constructor that accepts a list of parameters and initializes the instance variables using these values.
One last thing to note is the concept of constructor overloading
, where a class can have multiple constructors with different parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their types.