Java Instance Variable Initialization

1

June 30, 2012 by huionn

public class Init {
	
	public Init() {
		init();
	}

	protected void init() {
		
	}
}
public class SubInit extends Init {
	
	private int i = 0;
	
	public SubInit() {

	}
	
	@Override
	protected void init() {
		i = 2;
	}
	
	public static void main(String[] args) {
		SubInit si = new SubInit();
		System.out.println("value of i: " + si.i);
	}
}

What is the vaue of i?

It is actually 0!

	private int i = 0;
	
	public SubInit() {

	}

is actually equal to

	private int i;
	
	public SubInit() {
		super();
		i = 0;
	}

“i = 0” is executed after super’s constructor. Until today only I discover this from a mysterious bug.

Advertisements

One thought on “Java Instance Variable Initialization

  1. stargazer jt says:

    good sharing… 10s man

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: