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 Creating the MVP Prompting for Guesses

Brendan Passey
Brendan Passey
999 Points

Difference between a method and a constructor.

I'm really not sure what a constructor is used for. I know that it differs from a method in that a constructor requires you to pass in an argument.... But that's about all I know about it.... What is a constructor?

3 Answers

Steven Parker
Steven Parker
231,275 Points

A constructor is a special method that is automatically invoked when you create a new object instance, and never used for anything else.

A custom constructor can take arguments but the default one that the language provides for you when you don't write your own does not. And a constructor cannot return anything.

Ezekiel dela Peña
Ezekiel dela Peña
6,231 Points

The main difference between method and constructor is

Constructor can only be could when you are creating an instance of object.

public class Game {
   // This is a constructor
   public Game() {
   }

   // This is a method
   public void sampleMethod() {
   }
}

NOTE: by default when creating a class even if you didn't write a constructor, Java will do it for you.

Example:

Game game = new Game(); // <--- this how you create an instance of for example a Game.

Now remember how do you usually call a method?

game.Game(); // This will not work since Game() is a constructor which should only be called when creating an instance

Now a method is something you could call after creating an instance.

game.sampleMethod();
Brendan Passey
Brendan Passey
999 Points

Thanks guys I took a break and came back and worked through it all again. I understand this stuff now but thanks for the answers!