Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About constructors

I got a question about Constructors.I think constructors are all just our convenience instead of setter methods,right? So for an object , the properties you think important(such as required fields in a webform)are passed as parameters into constructor.

Is there any criteria that these many number of parameters should be passed into constructor? Please elaborate on these points and as well as any points about constructors.

Edit:Sorry about the way i asked question.Yes,we create an object with constructor and we assign values with setters but my question is about the comparison between default constructor with setters and constructor with explicit parametrs.

like image 585
Srinivas Reddy Thatiparthy Avatar asked Jan 18 '10 09:01

Srinivas Reddy Thatiparthy


People also ask

What is a constructor explain?

What Does Constructor Mean? A constructor is a special method of a class or structure in object-oriented programming that initializes a newly created object of that type. Whenever an object is created, the constructor is called automatically.

What is the main purpose of constructor?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method.

How do constructors work?

It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.


2 Answers

No, it's not just a convenience instead of setters. In particular, a constructor will only be called once. Using constructor parameters, you can create immutable types which are given their values at construction time - that wouldn't be possible with setters.

It's generally not a great idea to have huge numbers of parameters, whether to a constructor or a normal method. If you find you have a lot of parameters, you may want to create a type representing all the related ones - that type may have a bunch of getters/setters. See ProcessStartInfo for an example of this.

like image 122
Jon Skeet Avatar answered Sep 22 '22 23:09

Jon Skeet


I see it this way:

You pass the parameters in a constructor that are required in order to create an object that is in a 'valid' state.

For your example: I would not pass 'required fields in a webform' to the instance of the class that is filled up with those values.

like image 43
Frederik Gheysels Avatar answered Sep 25 '22 23:09

Frederik Gheysels