Java – All in One → Java Constructor – Camposha

Java – All in One

Java – All in One

Java – All in One

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Rating

Not enough ratings to display
Join Us
X