2. Java Object Oriented (7) _ Encapsulation Ideas - Selection of Constructor and Setter Methods

2018-04-30

 

Constructor and setter method selection

 

There are two ways to create an object and initialize it:

  1) First create an object through the no-argument constructor, and then call 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 an initial value (the setter method should still be provided, so that it is convenient to change the value )

    User u1 = new User("Lucy",18);

 

This can be done through both constructor and setter methods:

  Set data to the object:

  1) setter injection (property injection)

  2) Construct injection

 

How to choose these two ways:

Method:
  1. If there is a constructor with parameters, the second method is more concise (construction injection);
  2. If multiple data needs to be initialized when constructing the object (more parameters need to be constructed), if the second method is used, Then the constructor has to provide multiple parameters. There are too many parameters and it is not intuitive, so it is better to use the first method.
  3. Sometimes it is necessary to construct objects based on data. In this case, the constructor method is preferred (such as circle objects, how to draw circles, circle objects must be determined according to their radius: when building a circle object, the radius value should be determined) ).
  4, at other times optional.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168944&siteId=291194637