java-Constructors and Methdods

What is Constructor?

When the object is created, Java calls the constructor first. Any code you have in your constructor will then get executed. You don’t need to make any special calls to aconstructor method – they happen automatically when you create a new object. Constructor methods take the same name as the class.

Rules for creating java constructor

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

java constructor

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you don’t have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.