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;
}
Calling instance method in constructor is dangerous as the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on test-ability.
Constructors act like any other block of code (e.g., a method or an anonymous block). You can declare any variable you want there, but it's scope will be limited to the constructor itself.
All Java classes have at least one constructor even if we don't explicitly define one. In this article, we'll cover the behavior of the default constructor which sometimes causes confusion among new Java developers.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly. Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
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:
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared
static
are called static nested classes. Non-static nested classes are called inner classes.
In modern usage, there is no such thing as a "static member inner class".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With