Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods vs Constructors in Java

Tags:

I have just started programming with Java. The text we use is lacking when talking about methods and constructors. I'm not sure what a method or a constructor is exactly and what makes each unique. Can someone please help me define them and differentiate between the two?

like image 436
nckbrz Avatar asked Sep 27 '13 23:09

nckbrz


2 Answers

The important difference between constructors and methods is that constructors initialize objects that are being created with the new operator, while methods perform operations on objects that already exist.

Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new.

The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.

Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).

Methods must be declared to return something, although it can be void.

like image 121
rgettman Avatar answered Oct 16 '22 03:10

rgettman


The main difference is

1.Constructor are used to initialize the state of object,where as method is expose the behaviour of object.

2.Constructor must not have return type where as method must have return type.

3.Constructor name same as the class name where as method may or may not the same class name.

4.Constructor invoke implicitly where as method invoke explicitly.

5.Constructor compiler provide default constructor where as method compiler does't provide.

like image 22
murthy naika k Avatar answered Oct 16 '22 03:10

murthy naika k