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

Abhishek Ramchandran
Abhishek Ramchandran
1,063 Points

how to add a constructor with a string parameter

I have the task of adding a second constructor with a String parameter. I thought I had it right but the program thinks otherwise. Can you tell me what I have missed?

Spaceship.java
public class Spaceship {
    public String mType;

  public Spaceship () {
    mType = "SHUTTLE";
  }

  public setSpaceship (String typeOfShip) {
    mType = typeOfShip;
  }

    public String getType() {
      return mType;
    }

    public void setType(String type) {
      mType = type;
    }
}

2 Answers

Hi there,

In short, I think it is just a convention that works across multiple languages. It makes for clearer code and demands consistency in the creation of objects. It would help in examples of inheritance also making the code clear.

Java will create a default constructor for a class if you don't declare one explicitly. Java won't know you've done that unless you adhere to the convention. So, if you don't then the constructor won't get called at the point of instantiating an instance of the classas Java will use its own default constructor. Without this convention, the compiler won't know which method is a constructor and which are just instance methods so there needs to be a way of clearly defining that.

Make sense?

Steve.

Abhishek Ramchandran
Abhishek Ramchandran
1,063 Points

Yes, that was immensely helpful. Thanks so much!

Hi there,

You're pretty close. Both methods are constructors. One is a default one, which takes no parameters - you've done that correctly. Next, you want a constructor that takes a string parameter. Constructors are called the name of the class so the two constructors togetherwould look like:

  public Spaceship(){
    mType = "SHUTTLE";
  }

  public Spaceship(String type){
    mType= type;
  }

Steve.

Abhishek Ramchandran
Abhishek Ramchandran
1,063 Points

Yup, gotcha. Thanks a bunch, could you briefly explain the logic for why constructors are the name of the class itself? Appreciate it!