Trap of member initialization during Java Constructor

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. Running result



3. Cause

See http://blog.csdn.net/jltxgcy/article/details/17398751.

1. Call the parent class to initialize global variables. No global variables are required here.

2. Call the parent class constructor, which calls the member function preProcess of the subclass. 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 subclass.


4. Fan Wai

If the global variable whenAmISet does not set the initialization value, it is set to the default value. The object is null, And the int value is 0.

Local variables do not set initialization values. They must be displayed and cannot be used directly.

The initialization parameters must be displayed in the C ++ constructor initialization list. Different from Java.

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.