Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

java - Default constructor vs. inline field initialization

What's the difference between a default constructor and just initializing an object's fields directly?

What reasons are there to prefer one of the following examples over the other?

Example 1

public class Foo
{
    private int x = 5;
    private String[] y = new String[10];
}

Example 2

public class Foo
{
    private int x;
    private String[] y;

    public Foo()
    {
        x = 5;
        y = new String[10];
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Initialisers are executed before constructor bodies. (Which has implications if you have both initialisers and constructors, the constructor code executes second and overrides an initialised value)

Initialisers are good when you always need the same initial value (like in your example, an array of given size, or integer of specific value), but it can work in your favour or against you:

If you have many constructors that initialise variables differently (i.e. with different values), then initialisers are useless because the changes will be overridden, and wasteful.

On the other hand, if you have many constructors that initialise with the same value then you can save lines of code (and make your code slightly more maintainable) by keeping initialisation in one place.

Like Michael said, there's a matter of taste involved as well - you might like to keep code in one place. Although if you have many constructors your code isn't in one place in any case, so I would favour initialisers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...