Chris London
Chris London

Reputation: 81

What's the difference between constructors and passing parameters?

I believe I understand what constructors are now, but to me it seems they are just used for passing info to methods in another class. So why not just call a method and supply a parameter instead? Have I got this wrong?

Upvotes: 1

Views: 1791

Answers (3)

ssantos
ssantos

Reputation: 16526

Constructors are used to initialize new instance of an object, whenever you pass parameters or not.

Having parameters in a constructor is just a way to make it easy to set some initial attributes during the object initialization, which the object will most probably need in order to work as expected.

However, if those attributes weren't needed to be initialized for the correct operation of the instance object, it would make more sense not to pass them to the constructor, but just having some setters to pass them at any other time you need.

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

Constructors are used to create objects and are not ordinary methods. Whenever you use new to create an object, you actually call a constructor. For example:

new MyClass(); //here MyClass() is a constructor with no params

Note:

Constructor declarations look like method declarations—except that they use the name of the class and have no return type

Upvotes: 2

kelunik
kelunik

Reputation: 6908

If I understand it right:

Constructors are always called, so these attributes MUST BE passed. If you pass this info through methods they don't have to be passed, so they could be missing.

Upvotes: 0

Related Questions