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 The Model-View-Presenter Pattern Adding a Custom Constructor

Simon Riemertzon
Simon Riemertzon
862 Points

Trying to add a constructor, IDE thinks its a method!

I have checked and rechecked how to make a constructor in java and this should be the way.

public ClassName() {
 //Here you set variables you want to set when initializing. 
}

But trehouse-IDE is complaining about that it is missing a return type. Like it thinks its a method/function.

Does anyone see why it reacts that way?

Simon

Spaceship.java
public class Spaceship {
    public String shipType;

    public SpaceShip(){
      this.shipType = "SHUTTLE";
    }

    public String getShipType() {
      return shipType;
    }

    public void setShipType(String shipType) {
      this.shipType = shipType;
    }


}

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

Treehouse is giving you an error here because your class is called Spaceship, but your constructor is called SpaceShip (notice the capital "S" in "Ship"). Java is case-sensitive, so it interprets these as 2 unrelated names. You need to make these names match for Java to understand that you mean it to be a constructor for the Spaceship class.

However, you also have a bit of a conceptual error. Constructors are methods, but they're special methods whose return type is inferred and can only be called once to construct a new object. They're still full-fledged methods, though, and you can execute whatever code you want within them

Simon Riemertzon
Simon Riemertzon
862 Points

Got it!

That is a great explanation , thank you for your time!