Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What is the difference between these methods of construction

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();
    }
}
like image 647
MrHus Avatar asked Jul 25 '09 16:07

MrHus


People also ask

What is the difference between method and construction?

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.

What is different between constructors method in Java?

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.

What's the difference between constructors and void methods?

A void method specifically does not return any data or object. Pragmatically, a constructor does not return anything.

What is construction method in Java?

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.


2 Answers

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.

like image 149
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet


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.

like image 32
Silfverstrom Avatar answered Sep 18 '22 16:09

Silfverstrom