Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).
Methods must be declared to return something, although it can be void.
Let have a table to compare the differences between constructors and methods:
Constructor | method |
Used to initialize the state of object. | Expose the behaviour of object. |
Must not have return type | Must have return type |
Constructor name same as the class name where | method may or may not the same class name. |
Constructor invoke implicitly | Method invoke explicitly. |
Constructor compiler provide default constructor. | method compiler does't provide. |
Remarks
Text provided above does not means is the model answer, and it's was posted here for an reference to somebody who interested the related knowledge only. if there is something incorrect, please leave a comment so that i can correct it or for others viewer to have an better reference, if you want know more about this topic and where is the question, concept or answer from, you can reference from information provided under the reference sub-title.
Reference:
1) Introduction to Java Programming, Y. Daniel Liang
2) http://stackoverflow.com/questions/19061599/methods-vs-constructors-in-java
No comments :
Post a Comment