Difference between constructor and method

difference

Difference between method and constructor

The following are the difference between method and constructor.

  • Method name may or may not be the same as the class name whereas the constructor name must be same as the class name.
  • A method should have a return type in java where are constructor never returns any value, so it has no return type.
  • A method can be declared as static, final, abstract whereas this 3 keyword is not allowed for the constructor.
  • A method can be called by class name, object name or directly in Java whereas constructor name called by new, this and super keyword.
  • Java support method overriding where as constructor never support overriding in java.

PROGRAM:-

class Test

{

      Test()
      {

         System.out.println("constructor");

      }
        static void Test()

           {
          System.out.println("method");

           }

            public static void main(String[] args)

                {

                    Test();

                    Test.Test();

                    Test t1=new Test();

                    t1.Test();
                 }
};

O/P        method

                method

                constructor

                method

 

Example of the method is:-

class Test

{

                int x=10;

                static void show()

                {

                                System.out.println("I am in show method");

                }

                public static void main(String[] args) 

                {

                                show();                //call directly

                                Test.show();      //call by class name

                                Test t=new Test();           //object creation

                                t.show();             // call by object name

                }

}

 

 

O/P I am in show method

I am in show method

I am in show method

Example of a constructor is

Class Test
{

       Test(int x)
       {

         System.out.println(“I am in parameter constructor”);
       }

 public static void main(String[] args)
{

 new Test(123);
}


O/P  I am in parameter  constructor
basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community

8 thoughts on “Difference between constructor and method

Leave a Reply

shares