What is the difference between constructor and method?

What is the difference between constructor and method?

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

                  Constructor:

a)Constructor is used to initialize the state of an object

b)Constructor must not have return type.

c)Constructor is invoked implicitly

d)The java compiler provides a default constructor if you don't have any constructor.

e)Constructor name must be same as the class name.

             Method:

a)Method is used to expose behaviour of an object.

b)Method must have return type

c)Method is invoked explicitly.

d)Method is not provided by compiler in any case.

e)Method name may or may not be same as class name.
 

some differences are:

 1)Third difference between constructor and method in Java is that Constructors are chained and they are called in a particular order, there is no such facility for methods.

2)Unlike method, constructor, yet declared in class doesn't considered as member of Class. Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. on which case they are only visible in class on which they are declared. Similarly private constructor means you can not create object of that class from outside, this is one of the technique used to implement Singleton pattern in Java.

 3)Another difference between method and constructor in Java is that special keyword this and super is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them.
  

Read More →