-1

When we can use methods instead of constructor for any operation then what is the use of constructor in java or c++.

//Program of Division using constructor:-

class Hey {
    Hey() {
        int i = 10;
        System.out.println("Division of 10/2 is " + i/2);
    }
}
public class HelloWorld extends Hey {


     public static void main ( String[] args ) {

        Hey ob = new Hey();
     }
}

//Program of division using method:-

class Hey {
     public void disp() {
        int i = 10;
        System.out.println("Division of 10/2 is " + i/2);
    }
}
public class HelloWorld extends Hey {

     public static void main( String[] args ) {

        Hey ob = new Hey();
        ob.disp();
     }
}

As, we can see that both will have same output. So, now I am bit confuse that when to use constructor.

  • 3
    Constructors are used to create new objects. They should not be used to do calculations and display results. They mostly just set fields according to their parameters, and you can later use these fields to do calculations in methods – user Jun 07 '20 at 17:19

1 Answers1

1

Constructor is used to initialize objects in java. Even if you don't provide constructor in your code, java compiler will automatically add a default constructor.

Whereas Methods are used to exhibits functionalities to object. You will have to invoke methods explicitly in your code.

In the example you shared, you are creating object of Hey class Hey ob=new Hey() in order to call its method disp. So if you want to define object in your class, you will use constructors, and if you want to write some functionality of object, you can use Methods.

anmi
  • 21
  • 4