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 trialSimon Riemertzon
862 PointsTrying 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
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
47,913 PointsTreehouse 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
862 PointsSimon Riemertzon
862 PointsGot it!
That is a great explanation , thank you for your time!