Deep learning Java Constructors

Source: Internet
Author: User
Tags constructor inheritance

* From the inheritance of constructors, and related calls to think about, mainly from Java object-oriented programming

* In the case of multilevel inheritance, the constructor of each class is executed in sequence, starting with the parent class at the top of the inheritance tree.

This ensures that instances of the subclass object inherited from all direct or indirect parent classes are correctly initialized.

* When the constructor of a subclass does not have the constructor of the calling parent class displayed with the Super statement, and the parent class does not provide a default

The constructed method (the default construction method provided by the JDK) will cause a compilation error.

public class Grapha {
  // public Grapha() {
// System.out.println("Grapha()");
// }
  public Grapha(String name) {
 System.out.println("Grapha()");
}
}
  class Father extends Grapha{
  /**
* a compile error happen.
* implicit super constructor Grapha() is undifined,must explicity invoke another constructor
**/
public Father() {
 System.out.println("Father()");
}
/**
* a compile error happen.
* implicit super constructor Grapha() is undifined,must explicity invoke another constructor
**/
public Father(String name){
}
}

* From the above, if a class does not allow other programmers to use the new statement to construct its instance, and does not allow it to have subclasses, you can

Define all of its construction methods as private.

Another way to make a class incapable of having subclasses is to change the class declaration to final.

From the above can be thought of using static Factory mode:

* Single case mode (singleton)

* Enumeration Class

* Class with Instance cache

* Immutable classes with instance caching

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.