What's the difference between these two methods of initializing the observers ArrayList. Or any other type for that matter. Is one faster than the other? Or am I missing some other benefit here.
class Publisher implements Observerable
{
private ArrayList observers = new ArrayList();
}
class Publisher implements Observerable
{
private ArrayList observers;
public Publisher()
{
observers = new ArrayList();
}
}
Constructor is used to create and initialize an Object . Method is used to execute certain statements. A constructor is invoked implicitly by the System. A method is to be invoked during program code.
In Java, constructors must be called with the same name as the name of the class in which they live, whereas methods can have any name and can be called directly either with a reference to the class or an object reference. Constructors are an exception to this rule.
A void method specifically does not return any data or object. Pragmatically, a constructor does not return anything.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
They're equivalent. In fact, if you compile the two you'll see that they generate exactly the same byte code:
Publisher();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: new #2; //class java/util/ArrayList
8: dup
9: invokespecial #3; //Method java/util/ArrayList."<init>":()V
12: putfield #4; //Field observers:Ljava/util/ArrayList;
15: return
}
Given that they're the same code, there clearly can't be any speed difference :)
Note that in C# they're not quite equivalent - in C# the initializer for observers
would run before the base constructor call; in Java they really are the same.
Which you use is a matter of taste. If you have several different constructors which all initialize a variable in the same way it would make sense to use the first form. On the other hand, it's generally a good idea if you have several constructors to try to make most of them call one "core" constructor which does the actual work.
They are equal, but: the difference is that in the last example, you gain the benefit of being able to do more advanced initialization logic: error handling etc.
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