Constructor

Constructor is a special method in java. When method name is same as Class name, then its said as constructor. Constructor has no void or return type. It is used to initialize the object’s state

When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

There are two types of constructors in Java:
1. Default constructor
2. Parameterized constructor

1. Example of default constructor:

class Main {
    public static void main(String[] args) {
        new MyConstructor();

    }

}
class MyConstructor{
    public MyConstructor(){
        System.out.println("Calling default constructor");
    }
}
Output: Calling default constructor

2. Example of parameterized constructor:

class Main {
    public static void main(String[] args) {
        new MyConstructor("calling default constructor");

    }

}
class MyConstructor{
    public MyConstructor(String data){
        System.out.println(data);
    }
}
Output: calling default constructor
about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

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