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 Creating a Data Model

How do you add getters and setter in Android java?

How do I add a method to get the value of mType in the following code?

Spaceship.java
public class Spaceship {
  public String mType;

  public String getter {
    return mType;
  }
}

3 Answers

Dan Johnson
Dan Johnson
40,533 Points

You almost have it. All you'd need to do is add a set of parentheses after the method name to make the code compile. However you'll also want to change the name of the method so it better describes what it's getting. Here's the standard format:

// "getPropertyName" for getters
// "setPropertyName" for setters
// prefix is ignored if one is being used

public String getType() {
  return mType;
}

Thanks Dan, had rushed through the lesson without paying attention. It worked !!! thanks

David Anton
PLUS
David Anton
Courses Plus Student 30,936 Points

If you are using Android Studio you can navigate to your class and then:

Windows: HOLD Ctrl + N

MAC: HOLD Command + N

  • Click on "getters and setters"
  • Checkbox witch property you want to generate it's getters and setters