How to call a constructor?

593    Asked by Papuii colneyChauhan in Java , Asked on Oct 13, 2022

 After reading about theory and Q&As about constructors I am struggling to fully understand them. I know how to call a constructor and how to call a method, but I cannot rationalise this.

A constructor has to be called directly when ...

Constructor overloading will be done when ...

Methods will be called directly by calling the default constructor when ...


Answered by Parth Joshi

How to call a constructor can be answered as -


You call a constructor when you want to create a new object instance. For example if you have a class Button, then you call the constructor if you want to create a new Button instance.

If you don't need a new object, then don't use a constructor. In your example you just use the constructor as a convoluted way of calling a method, but you don't actually use the created object (the result of the new-expression) for anything. This is a clear hint that you don't need to call a constructor. If you made saySomething static you would not need to call any constructors.

The reason for your confusion is probably that the HelloWorldConstructor class does not really have any purpose beyond writing output. Therefore it is not obvious whether you should have one or two instances of it. In reality you don't need any instance at all.



Your Answer

Interviews

Parent Categories