Ii. Java Object-oriented (7) _ Encapsulation idea--the choice of constructor and setter method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.