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

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,661 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.