Difference between method and constructor?

9

Reading the notes of a friend I came across the following statement: "method does not allocate space in memory". Is this statement correct?

Maybe it's not the main difference between them, but it's true to say that constructors allocate space in memory, whereas methods do not?

    
asked by anonymous 18.12.2015 / 17:20

1 answer

5

Depends on context. Constructor is a method. Every method takes up a space in memory where your code is. But I guess that's not quite what he means.

What he probably meant was that the constructor allocates a space in memory to hold the data of the object it is building. And that method never does this. If so, yes, that's right, at least roughly yes. The thing may be a bit more complex.

If a common method creates a new local object to the method, is it allocating space in memory, or not? Indirectly it is. If you find that running a method will never increase the amount of space in memory, you are making an error. Of course directly the allocation will be done by a constructor of this object within the method we are talking about.

But we can still do another analysis. The builder does not allocate anything. Who allocates is the memory manager of the JVM. The constructor only fills this space with data. So strictly speaking, it is wrong. But you can understand what the statement means, even if it is not accurate.

It probably means that constructors create objects and populate them with data (even though defaults ) and common methods just manipulate the data into existing objects.

Constructors have their own syntax to declare and call them.

Because they are used to create objects, important implications for inheritance .

See more about builder use . When they are called .

Related .

    
18.12.2015 / 17:28