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

Sølvi Qorda
Sølvi Qorda
14,194 Points

"Make sure you set 'mType' in your constructor"

Hey,

I'm really stumped as to why this code keeps pulling up problems.Any ideas? Many thanks in advance.

public class Spaceship { public String mType;

public String type( )  {
mType = "SHUTTLE";
return mType;
}

public String getType() {
  return mType; }

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

}

2 Answers

Kevin Faust
Kevin Faust
15,353 Points

Hi,

You need two constructors and not just one:

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

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

Our first constrcutor takes nothing and will assign mType to be SHUTTLE. Our second constructor takes in a string and our mType variable will be equal to our string.

public String type( )  {
mType = "SHUTTLE";
return mType;
}

What you have doesnt make sense. Constructors always consist of only the class name. You never "return" anything in the constructor either

Sølvi Qorda
Sølvi Qorda
14,194 Points

Thanks Kevin, that worked, though I'm still confused, but maybe I just need more practice.

Kevin Faust
Kevin Faust
15,353 Points

No problem. And this is something called Constructor Overloading where we have two different constructors accepting different values. I encourage to check out the java track if you find yourself having difficult in the future. You will learn this in that track in a bit more detail.