1.

Constructor vs Method

Answer»

The following is the difference:

BasisConstructorMethod
Return typeConstructors in Java have no return type, not EVEN VOID.Methods in Java ALWAYS return a value or they are void
NomenclatureConstructors have same name as the classMethods have any other legal name apart from the class name
Relation with ObjectsConstructors are used to initialize the state of the objectMethods are used to show the behavior of the object
OverridingConstructor overriding is not possible in JavaMethod Overriding is possible in Java
StaticConstructors can never be declared as staticMethods can be declared as static
InvocationConstructors are only invoked when an object is created using the ‘new’ keywordMethods are invoked by a class name,their own name or by an object.
ExecutionConstructors will be executed only one time per objectMethods 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


Discussion

No Comment Found