2018-04-30
constructor and setter method selection
There are two ways to create an object and initialize an object:
1) First create the object through the parameterless constructor, and then invoke the corresponding setter method through the object
eg
User U1 = new user ();
U1.setname ("Lucy");
U1.setage (18);
2) directly call the constructor with parameters, then the created object will have the initial value ( or to provide setter method, so as to facilitate the change of value )
User U1 = New User ("Lucy", 18);
This functionality can be accomplished through both the constructor and setter methods:
To set data for an object:
1) Setter Injection (attribute injection)
2) Construction Injection
How to choose both of these options:
Method:
1, if there is a constructor with parameters, then use the method of two more concise (construction injection);
2, if you need to initialize multiple data when building objects (need to construct more parameters), if using mode two, then the constructor has to provide multiple parameters, too many parameters, not intuitive, then use a better way.
3, sometimes need to base on the data to build objects, at this time preferred to use the constructor method (such as circular objects, how to draw a circle, the circle object must be based on the radius to determine the object: it should be in the construction of the Circle object, it is necessary to determine the radius value).
4, other time optional.
Ii. Java Object-oriented (7) _ Encapsulation idea--the choice of constructor and setter method