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

Java Java Objects (Retired) Harnessing the Power of Objects Incrementing and Decrementing

So what is actually differentiating between a constructor and a method?

From the examples so far it seems the only thing differentiating the two is the fact that a constructor share the same as the class. Is that how a constructor is defined?

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Ivan;

The easiest way I have found to explain the difference was in a post at StackOverflow:

The important difference between constructors and methods is that 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.

Post back with additional questions.

Ken

Thanks for the answer Ken. That helps a lot.