|
Answer» The following is the difference: | Basis | Constructor | Method |
|---|
| Return type | Constructors in Java have no return type, not EVEN VOID. | Methods in Java ALWAYS return a value or they are void | | Nomenclature | Constructors have same name as the class | Methods have any other legal name apart from the class name | | Relation with Objects | Constructors are used to initialize the state of the object | Methods are used to show the behavior of the object | | Overriding | Constructor overriding is not possible in Java | Method Overriding is possible in Java | | Static | Constructors can never be declared as static | Methods can be declared as static | | Invocation | Constructors are only invoked when an object is created using the ‘new’ keyword | Methods are invoked by a class name,their own name or by an object. | | Execution | Constructors will be executed only one time per object | Methods can be executed a number of time per object |
An example program to show the use of constructor and method is as follows: PUBLIC class Example
{
Example()
{
System.out.println("You are in a constructor");
}
public void PRINT()
{
System.out.println("You are in a method");
}
public static void main(String []args)
{
Example e = new Example();
e.print();
}
}The output for the following is as follows: $javac Example.java
$java Example
You are in a constructor
You are in a method
|