Friday, June 19, 2009

Difference between Constructors and Methods

Difference b/w Constructors and Methods

Question

What does a constructor meant for? And how it differs from methods?

Answer

Constructor is to create instance of a class, you may call it as "creating an object". While methods are just to execute a piece of java code. Constructors and methods differ in three aspects of the signature: modifiers, return type, and name.

--> Constructors dont have return types, not even void.

--> Like methods, Constructors can have any of the access modifiers: public, protected, private or none. But unlike methods, they cannot be abstract, final, native, static or synchronized.

--> Name of the constructor is always same as that of the Class to which it belongs to, while methods normally have names other than their class name.



For Further Reading:

http://www.ccnyddm.com/AdvJava/java_constructor_tutorial.htm

No comments:

Post a Comment