Saturday, October 1, 2011

What's the difference between constructors and normal methods?

Constructor:
It is automatically invoked when an object is created of a class. It has the same name of its class. Constructor is invoked by using new operator and it has no return type. A constructor can be overloaded but can not be overridden. Default constructor is automatically generated by compiler if class does not have once.

Example: 

Class A
{
     A()
  {
    System.out.println( " this is an example of constructor" );
  }
}
 
Method:

It is just an ordinary member function in a class. Method is invoked by using a dot(.) operator. It has its own name and return type.

Example:

class A
{
    voidDisplay()
  {
      System.out.println(" This is an example of method ");
  }
}

Find more about this question click here

No comments:

Post a Comment