I’m undertaking a ‘static’ code walkthrough of Java code from a colleague (another student)
To me, this doesn’t make sense; reading from top to bottom these ‘component’ objects are instantiated (and later used in the constructor) before they are declared. But, the code happily compiles and runs. Is this bad practice?
Public Class theObject {
private static final long aVariable = 123123123123123;
public theObject(...){
componentOne = new Component(...);
componentTwo = new Component(...);
...
...
componentOne.doSomething(...);
}
private Component componentOne;
private Component componentTwo;
}
Sun Microsystems (now taken over by Oracle) published its Java Coding Style Guide in 1998, in which they recommended a particular organization to class declarations:
Note that this puts the data declarations at the top of the file. (An earlier Sun publication from 1997 did not cover everything in the above list.) The only important ordering is within the static fields and within the instance fields, and then only if the fields contain initializers that refer to other fields. You cannot use a field in an initializer before it itself has been initialized. Similarly, an initializer (item 3 or 6) cannot make a forward reference to a field, except as the target of an assignment. (See the Java Language Specification, Section 8.3.3, for more information on such forward references.) As far as I know, nothing else about the order matters.
[*] The terminology in the above list (which is verbatim from the 1998 guide) is out of date with regards to items 4 and 8. Specifically, from the Java tutorial on nested classes:
In modern usage, there is no such thing as a “static member inner class”.