Johnny Johnny - 1 year ago 81
Java Question

Need of a constructor? (Java beginner)

clarification in edit below

Hey I'm a beginner in java and i was hoping someone could explain to me the difference in setting a value in a class (if there are any).

So is there any difference with this:

public class Something{
private int some;

public Something() {
this.some = 10;

and this (except that one uses more code)?:

public class Something{
private int some = 10;

Thank you for all the answers but there seems to be a misunderstanding as to what I exactly meant for which I can only blame myself. But let me clarify that.

So what I was wondering was if there was any difference in respect to optimisation, style and potential errors, when wanting to hard code, for example, a starting value which would always start being the same value but could potentially change from other methods.

Answer Source

There is practically no difference between those two class structures. In the first case the constructor is executed before the object finishes being initialized, ensuring some is set by the time new Something() returns. In the second some is set before the implicit default constructor is called. At a low level the order of operations here is slightly different but almost all users do not need to care.

It sounds like the reason you're asking is for performance concerns. This is an unhealthy way to think about programming. Except in very particular use cases (e.g. the Apollo space missions) you should prioritize code quality over rote efficiency. Trying to optimize your code for when a single assignment occurs should be very low on your list of priorities, because real algorithmic changes will vastly overshadow these sorts of optimizations. For example reading a file takes many orders of magnitude more time than variable assignments. If you can remove a single file-read from an application you'd likely improve its efficiency by more than all of the benefit a change like this might afford.

Over-eager optimization is a source of countless bugs, and a common topic in software design, some resources on that topic:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download