Some knowledge of constructors in Java

The constructor of Java plays a very important role. Firstly, the constructor in Java can be overloaded, and because it can inherit the constructor of the parent class, in the subclass, the constructor of the parent class must be called first. See the following two examples for comparison:

The final output of this example is

A without any parameter

B with a parameter

You can see that the constructor of the parent class is called first, and then your own constructor is called. However, because the parameterized constructor in class B here has no super parent class, it will only execute the parameterized constructor of the parent class. If you want it to execute the constructor of the parent class with parameters, write the code as follows:

So the final output is:

A with a parameter

B with a parameter

Therefore, the derived class must call the constructor of the parent class with parameters through super. One more question is attached below:

What is the output?

First, let's analyze the problem:

Because first look at the main function, the main function has only one code: new test(); Because it is found that this test class inherits from X, first construct x, then run class X, y B = New Y (), then we can see the output y, and then execute the constructor of class X to output X; Next, construct y, then execute test's own constructor and output Z, so the output result is yxyz.

The above detailed explanation of some knowledge about constructors in Java is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>