Explain the construction method call under Java inheritance in detail

Explain the construction method call under Java inheritance in detail

When creating an object of a class in Java, if the class has a parent class, call the constructor of the parent class first, and then call the constructor of the child class. If the parent class does not define a constructor, the compiler automatically creates a default constructor without parameters. If the parent class defines a public parameterless constructor, the parameterless constructor will be called automatically before calling the constructor of the child class. If the parent class has only a constructor with parameters and no constructor without parameters, the child class must explicitly call super (parameter list) in the constructor to specify a constructor with parameters. If the parent class defines a parameterless constructor, but the parameterless constructor is declared private, the subclass must also explicitly call super (parameter list) in the constructor to specify a parameterless constructor. If the parent class has no other parameterized constructor, the child class cannot be created.

For example:

When a child object is created, it will first call the constructor of the parent class to initialize pstring to "P1", and then call the constructor of the child to initialize CString to "C1".

Since the parent class defines a private parameterless constructor, it must be explicitly specified in the subclass to call a parameterless constructor.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

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
分享
二维码
< <上一篇
下一篇>>