Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jiten Mistry
4,698 PointsWhat is the difference between methods and constructors in java?
Finding it difficult to understand the difference between the two, and why we used a constructor over a method. Also why do we put parameters in a constructor different to the variable we are using?
2 Answers
Ken Alger
Treehouse TeacherJiten;
Welcome to Treehouse!
This can indeed be a confusing subject.
The important difference between constructors and methods are:
- Constructors create and initialize objects that don't exist yet, while methods perform operations on objects that already exist.
- 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.
Hope it helps, post back if you need additional insight.
Ken
Clinton Johnson
28,714 PointsThank you so much for this explanation I was reviewing my study notes and got confused because as you stated Constructors/Methods look the same in coding. However they was you explained it makes clear sense
Thank you.....
Ken Alger
Treehouse TeacherClinton;
Pleased it helped.
Ken