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

Explain Methods and constructors for me please.

Learning java. finished basic course and half way through java objects. Still pretty unclear what a constructor is :/ im hopeless at googling

2 Answers

Great question.

https://stackoverflow.com/questions/19061599/methods-vs-constructors-in-java#19061630

This thread will help...

here is an excerpt:

"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."

Thank you very much! Great explaination! Would u care to help me again, how do i open jshell? he keeps saying "open jshell" but i cant remember how to do it :/

Hi!

In the workspace you should be able to just type jshell at the command line.

Thank you for the help Todd!