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

Andy Stevens
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Andy Stevens
Front End Web Development Techdegree Graduate 20,417 Points

What’s the difference between a method and constructor in Java? They seem very similar and this keeps tripping me up.

I’m new to OOP, while I understand the concept my biggest stumbling block is definitely methods and constructors. Does anyone have any suggestions of learning strategies I can use to solidify my understanding?

1 Answer

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

The main difference between method and constructor is

Constructor can only be called 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();