Java constructor

Posted in Java By Raj On December 4, 2017

 

When you want to initialize fields while creating object then we can go for constructor,  normally the constructor will be invoked by the new operator after the memory is allocated for the new object, the constructors should have the same name as the class name

The constructor that does not take any parameters is called default constructor, if we don’t provide any constructor to the class then the default constructor will execute, the default constructor will be executed when we create an object something like this

Private constructor in java

If you don’t want to create object for the class then what you can do is right make a constructor as a private contractor, while creating object for the below class you will get compile time error

Constructor types in Java

  • Default Constructor
  • parameterized constructor

The default constructor does not take any parameters, example for default constructor is below

The constructors which take parameters is a parameterized constructor, check below code

Output :

Constructor overloading

Like method overloading, you can also have constructor overloading something like below