Talk about constructors in Java

Source: Internet
Author: User

This blog post is primarily for beginners, people interested in the Java language and those who have not systematically learned the basics of Java in a summary, in the article on the structure of the detailed description and discussion, but also contains my personal views of the Java object-oriented constructor function. Those who wish to walk on the path of Java learning can have a clearer understanding of it. Of course, only for personal opinion, the level is limited, the shortcomings, but also please point out that the exchange of learning with each other.

  1. Concept of constructors

A lot of Java novice talk about the constructor will be dizzy, we first look at what is a constructor function.

First, the constructor is a special form of the function, where is it special? The constructor does not need to define the return type (void is not required to return the value of the meaning, note the distinction between the two), and the name of the constructor is exactly the same as the class name, the rest of the function is the same as the attributes, you can have a parameter list, you can have the overloaded behavior of the function.

  2. Format of the constructor

Understanding the basic concept of the constructor, now to write a constructor, I hope you can understand, remember its format, through an example to find its differences with ordinary functions.

public class demo{

num=0-Private int;

03//No parameter constructor

Demo ()

05 {

System.out.println ("Constractor_run");

07}

08//Parametric constructor

Demo (int num)

10 {

System.out.println ("Constractor_args_run");

12}

13//General member function

public void Demofunction ()

15 {

System.out.println ("Function_run");

17}

18}

To illustrate here, if we do not declare constructors in a class, the JVM will help us to generate a constructor for the null argument by default, and if we declare a constructor with a parameter list in the class, the JVM will not help us to generate a constructor for the null argument by default. If we want to use the constructor of an empty argument, we have to explicitly declare the constructor of an empty parameter.

  3. Function of constructors

By the beginning of the introduction, the outline of the constructor is gradually clear, then why there is a constructor? What is the function of the constructor? The constructor is the object-oriented programming idea needs, its main function has the following two:

1) Create the object. When any object is created, it needs to be initialized for use, so any class that wants to create an instance object must have a constructor.

2) object initialization. The constructor can initialize the object, and it is a certain initialization function to initialize the object in accordance with its format (parameter list).

  4. The difference between a constructor and a normal function

The following is a detailed analysis of the difference between the constructor and the ordinary function, through a comparison of the two, we hope to deepen the understanding of the concept of the constructor function.

1) different formats:

The constructor does not have a return type, and the function name matches the class name of the class in which it exists;

The normal function has a return type, and the function name can be named according to the requirements.

2) Different call times

The constructor is run when the object of the class is created;

The normal function executes when the object is called.

3) Different execution times

Once an object is created, its constructor executes only once, which is executed when it is created;

Once an object is created, its normal function can be executed more than once, depending on the number of calls to the object.

  5. Usage Scenarios for constructors

When we analyze the information of so many constructors, when do we use constructors? Since the constructor is the initialization of the new object, when the development of the analysis of things, when the discovery of things have some characteristics, it can be defined in the constructor, so convenient, but also conform to the object-oriented programming ideas.

  6. Characteristics of constructors in inheritance

In inheritance, objects created by subclasses can invoke the public methods and properties of the parent class, then will the subclass call the constructor of the parent class? What does a subclass's constructor have to do with the constructor of the parent class? What do the constructors of subclasses need to be aware of? Here are some answers to these three questions.

1) will the subclass call the function of the parent class?

Subclasses inherit the parent class, and the constructor of the parent class executes when the subclass object is initialized, because the subclass needs to use the attributes in the parent class, and the subclass needs to know how to initialize it, so the subclass initialization will necessarily call the parent class's constructor (unless the parent class has no attributes, the description of the class is too poor, Or there's no need to create this class.)

2) What is the relationship between the constructor of the subclass and the constructor of the parent class?

The default first line in the subclass's constructor has an implicit statement super (), which accesses the null argument constructor in the parent class, unless there is no constructor for the null argument in the parent class, then the first row of the subclass constructor must explicitly call the parent class's constructor, the super (int x,...).

3) What is the problem with the constructor of the subclass?

In the constructor for a subclass, the super () statement represents the constructor that called the parent class, and the This () statement represents the constructor that called the subclass itself. Note that if these two statements are explicitly written out to be placed in the first row of the construction method, and the two statements cannot coexist, the first row in a constructor is either this () or super ().

Why on the first line? Because it needs to be initialized first.

Why can't we coexist? Because this () represents the other constructors of this class, it will also go to call super (), there is no need for this () to appear again super (), repeated calls meaningless. In other words, at least one of the constructors at the beginning of a subclass is super (), which can of course be implicitly present, meaning at least one of the constructors does not begin with this ().

  7. Extension of the constructor function

The above six has been described in the concept of the structure function, characteristics, use and other issues are relatively clear, below to introduce a few of the extension of the constructor function of the small knowledge.

1) Do all classes have constructors? Can constructors be privatized?

Since constructors are used to create objects and initialize objects, there is no need to define constructors when a class does not need to create objects, but in Java all classes have constructors, but some of them are invisible to the developer, which is not what we expected. But that's a good idea, because Java is object-oriented, and the purpose of creating classes is to create objects or to create their child class objects, so there's no sense in classes without constructors (classes that can't create objects).

For the second problem, when a class does not want the outside world to create its objects, it can privatize its constructors, provide methods for returning objects in this class, and provide unique objects in most cases, and a singleton design pattern is a good example, and when we need to ensure the uniqueness of the object in our development, This approach is often taken.

2) What are the similarities and differences between constructing a block of code and a constructor function?

The construction code block is represented by a pair of "{}", where there is no specific requirement for the code block location, but must be the same level as the members of the class, within the brackets, all objects of that class can be initialized, that is, when the class object is created, it is executed to that code block, and it takes precedence over the constructor. constructors, as mentioned earlier, are targeted, and construction blocks of code are scoped to all objects of this class.

Talk about constructors in Java

Related Article

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.