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 Meet Objects Add a Constructor

Ben Bellis
Ben Bellis
2,017 Points

I don't understand constructors

I'm completely stalled on constructors. I don't understand how to create or define them and I've watched the video multiple times over the past couple of days. would anybody be able to simplify as basically as they can?

1 Answer

Mathew Tran
PLUS
Mathew Tran
Courses Plus Student 10,205 Points

A Constructor is a function that is called upon creation of an instance of an object. This is where you would usually initialize values.

To create a constructor you need to make a method that returns the class that you are creating. It also needs to be defined within scope of the class.

The scope of the class is the code that is in between the curly braces

class GoKart
{
// This is the class scope where I should define my constructor!
}

This is how to create a constructor, when in class scope.

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

In the terms of the challenge, it's the same as adding parameters to any other functions. Just add the color attribute of type String as a parameter to the constructor

Hope this helps!

Matt