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
MOD
Michael Hulet
Treehouse Moderator 46,955 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!