Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build an Interactive Story App (Retired) The Model-View-Controller Pattern Adding a Custom Constructor

Ernest Lin
Ernest Lin
2,691 Points

How do you make a constructor?

How do you make a constructor? I still don't get this...

2 Answers

Kristian Gausel
Kristian Gausel
14,649 Points

The constructor of a class named ClassExample will look like this:

public ClassExample (){


Where you can have arguments inside the parenthesis as with any other method.

Daniel Maia
Daniel Maia
6,228 Points

Kristian is correct, a simple empty default constructor is created as per above.

However, when you create a class, you can think of a car, as an example. So, the questions you should ask yourself are:

  1. Make of the car?
  2. Model of the car?
  3. Number of doors?
  4. Color of the car? etc.

Now this may look something like this:

public class BMW {

  public String mMake;
  public String mModel;
  public int mNumberOfDoors;
  public String mColor;

  // The Contructor will be used when the class is initiated
  public Car(String make, String Model, int doors, String color) {
     mMake = make;
     mModel = model;
     mNumberOfDoors = doors;
     mColor = color;

// Below you would of the rest the code such as setters and getters etc. 


As you can see above the constructor would be the first thing created when you create the Car object. Now if I was to create this class it may look something like this:

Car myNewCar = new Car("BMW", "Z4", 3, "Silver");

Now the myNewCar object will contain the properties of BMW, Z4, 3 and SIlver to which can then be used later on for other things.

I hope this is clear, if you have any questions let me know.