Constructor:
A constructor is a special method that is used to initialize that is used to initialize an object. The java constructor is a special method it looks like a method but it is not a method. The constructor shares the class name and will not have any return type even void also. The java constructor is invoked at the time of object creation. The constructor overloading is possible.
There are two different types of constructors in java
Default constructor
User-defined constructor
Default constructor
The default constructor is provided a compiler that has no parameters and default returns 0; null.
Example:
class sample{
sample() // Default constructor
{
System.out.println(“sample is created”);
}
public static void main(String args[ ]){
sample s = new sample();
}
}
User-defined constructor
The user-defined constructor is also known as parameterized constructor. A constructor that have parameters is known as parameterized constructor.
Example:
class Sample{
int id;
String name;
Sample(int i,String n){ //user-defined constructor
id = i;
name = n;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]){
Sample s1 = new Sample(1,"Raju");
Sample s2 = new Sample(2,"Ramu");
s1.display();
s2.display();
}
}
The differences between constructor and method
Java constructor
|
Java method
|
Constructor doesn’t have any return type even void
|
Method have return type and sometimes we can use void
|
The java complier provides a default constructor if a class doesn't have any constructor
|
The java complier doesn’t provide any default methods.
|
Constructor shares class name
|
Method name may be or may not be same to class name
|
Constructor invoked at the time of object creation.
|
Method is invoked explicitly.
|
Two types of constructor in java default and user defined.
|
Static and private, final and public like these different types of methods are there in java.
|
EmoticonEmoticon