Types Of Constructor in Java
In Java, there are three types of constructors:
Default Constructor: A default constructor is a constructor with no parameters defined. It is automatically created by the compiler if no constructor is defined in a class.
Parameterized Constructor: A parameterized constructor is a constructor with parameters defined. It is used to initialize the values of instance variables of a class with the values passed as arguments while creating an object of that class.
Copy Constructor: A copy constructor is a constructor that creates an object by copying the values of another object of the same class. It is used to create a new object with the same values as an existing object.
Here's an example of each type of constructor:
java with mohit// Default Constructor
public class MyClass
{
public MyClass()
{
// Constructor code here
}
}
// Parameterized Constructor
public class MyClass
{
private int value;
public MyClass(int val)
{
value = val;
}
}
// Copy Constructor
public class MyClass
{
private int value;
public MyClass(MyClass obj)
{
value = obj.value;
}
}
Comments
Post a Comment