Difference between method and constructor?

Asked

Viewed 1,648 times

11

Reading a friend’s notes I came across the following statement: "method does not allocate space in memory". This statement is correct?

It may not be the main difference between them, but it is correct to say that constructors allocate space in memory, while methods do not?

1 answer

6


It depends on the context. Constructor is a method. Every method occupies a space in the memory where it is your code. But I don’t think that’s exactly what he means.

What he probably meant is that the constructor allocates a space in memory to contain the data of the object he is building, and that the method never does this. If this is it, yes, that’s right, at least roughly yes. It can be a little 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 space occupied in the memory is making a mistake. Of course directly the allocation will be being made by a constructor of this object within the method we are talking about.

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

It probably means that constructors create objects and fill them with data (although defaults) and common methods only handle data on existing objects.

Constructors have their own syntax to declare them and to call them.

For being used in the creation of objects exist important implications for inheritance.

See more about the use of builders. When they are called.

Related.

  • Interesting answer. Reading the Caelum booklet (p. 79): "A builder is not a method. Some people call it a special method, but it definitely is not, since it has no return and is only called during the construction of the object". I was left with doubt and I thought that a reply to this answer would suffice. My understanding was that it is a method, and it has a return: an object, with a self-reference of this. Moreover, void methods also have no return, which would invalidate that statement. It makes sense?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.