Constructor is a special type of method that
automatically calls when an object is created. Constructors are mainly used to
initialize objects. We can also initialize an object with the help of methods,
for example setData().
Rules for Creating Constructor
- Constructors have the same name as the class itself.
- Constructor has not any return type, even void.
- Constructors can have access modifier.
Types of Constructor in Java
There are two types of constructor in java.
Java No-Argument Constructor
A constructor that has no parameter is known as no-argument constructor.
No-argument constructor is also known as default constructor. If we don't
create any type constructor in a class, then compiler automatically creates default
constructor. But if we define any type of constructor, then compiler does not
create any constructor. Compiler created constructor initialize an object to
the default value, depends on its data members.
Example of Java No-Argument Constructor
class Testing
{
String name;
int id;
Testing()
{
System.out.println("A default constructor has no parameter");
}
}
class DefConstructor
{
public static void main(String[] args) {
Testing t = new Testing();
}
}
Output:
A default constructor has no parameter
Java Parameterized Constructor
A constructor that has parameters is known as parameterized
constructor. A parameterized constructor can have one or more parameters.
Example of Java Parameterized Constructor
class Testing
{
String name;
int id;
Testing(int x, String n)
{
id = x;
name = n;
}
void showData()
{
System.out.println("Id : "+id+"\nName : "+name);
}
}
class DefConstructor
{
public static void main(String[] args) {
Testing t = new Testing(1, "Bill");
t.showData();
}
}
Output:
Id : 1
Name : Bill
Constructor Overloading in Java
A class can have any number of constructors. Compiler differentiates constructors by number of parameters and type of parameters and order of constructors in which they are defined.
Example of Constructor Overloading in Java
class ConOverloading
{
ConOverloading()
{
System.out.println("Default constructor is running");
}
ConOverloading(int x)
{
System.out.println("Parameterized constructor is running");
}
ConOverloading(ConOverloading c)
{
System.out.println("Copy constructor is running");
}
public static void main(String[] args) {
ConOverloading c1 = new ConOverloading();
ConOverloading c2 = new ConOverloading(10);
ConOverloading c3 = new ConOverloading(c1);
}
}
Output:
Default constructor is running
Parameterized constructor is running
Copy constructor is running
0 comments:
Post a Comment