Java Constructor


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

  1. You don't specify any return type. This is unlike ordinary methods.
public class MyClass{
    //Our constructor
    public MyClass() { }

}
  1. 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.

  1. Constructors can have accessibility modifiers. We can control their visibility just like we can with methods. This means constructors can be private,public or protected.

  2. 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

  1. Constructors provide us with a way to automatically listen to class instantiation so as to do any imaginable thing like say initializing values etc.
  2. Constructors allow us inject dependencies from the outside world into our class as parameters.
  3. 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

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post