A trap for member initialization when Java constructs

Source: Internet
Author: User

1. First list the code

Base.java

public class base{    Base () {        preprocess ();    }     void Preprocess () {}}

Derived.java

public class Derived extends base{public    String whenamiset = "set when declared";     @Override void Preprocess ()    {        Whenamiset = "set in Preprocess ()";}    }

Main.java

public class main{public    static void Main (string[] args)    {        Derived d = new Derived ();        System.out.println (D.whenamiset);    }}

2. Implementation results



3. Reason

The http://blog.csdn.net/jltxgcy/article/details/17398751 can be tested.

1, call the parent class global variable initialization, there are no global variables and do not have to initialize.

2, call the parent class constructor, inside called the subclass member function PREPROCESS,WHEnamiset is set to "set in Preprocess".

3, call the subclass global variable initialization, Whenamiset is set to "set when declared".

4. Call the constructor of the child class.


4, Pan outside

Assuming that the global variable is whenamiset, no initialization value is set. Then it is set to the default value.

The object is null,int to 0.

Local variables. The initialization value is not set. The settings need to be displayed and cannot be used directly.

The C + + constructor initialization list must display an initialization parameter.

is different from Java.

A trap for member initialization when Java constructs

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.