A constructor is a special type of method that gets invoked automatically whenever a class is instantiated.
Instantiation is the process of creating an Object of a class.
Characteristics of Contsructors
- You don’t specify any return type. This is unlike ordinary methods.
public class MyClass{
//Our constructor
public MyClass() { }
}
- Constructors must use the class name as their name.
public class MyClass{
//Our constructor
public MyClass() { }
}
Like in the above our constructor name is MyClass
just like our Integer name.
- Constructors can have accessibility modifiers. We can control their visibility just like we can with methods. This means constructors can be
private
,public
orprotected
. - Constructors can take in parameters/arguments like methods.
public class MyClass{ //Our constructor public MyClass(String name,int id) { }
}
Like in the above our constructor takes in an [Integer](/java/integer) and a [String](/java/string).
5. Constructors implicitly return a the class instance.
```java
public class MyClass{
//Our constructor
public MyClass(String name) { }
}
public class AnotherClass{
String name="Oclemy";
//Get MyClass instance,pass name in constructor
MyClass myClass=new MyClass(name);
}
Advantages of Constructor
- Constructors provide us with a way to automatically listen to class instantiation so as to do any imaginable thing like say initializing values etc.
- Constructors allow us inject dependencies from the outside world into our class as parameters.
- Constructors construct for us a class instance, basically return us a class object.
Example
Here is an example
class MyClass{
//class constructor
public MyClass(String name) {
System.out.println("My name is "+name);
}
}
class AnotherClass{
//main method
public static void main(String[] args) {
MyClass myClass=new MyClass("Oclemy");
}
}
RESULT
My name is Oclemy