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

Java Java Data Structures Getting There Class Review

Instead of not creating a setter to make the member variables immutable. Why can't you just declare it final

example:

instead of: private String mAuthor;

why not: private final String mAuthor;

1 Answer

Gustáv Szilárdy
Gustáv Szilárdy
3,949 Points

private String mAuthor; Using the setter you can set mAuthor many times in your code.

private final String mAuthor;

  • You have to initialize mAuthor: right in the class or in the default constructor.
  • In another code can not be changed.
// RIGHT IN THE CLASS
public class Treet {
  private final String mAuthor = "Dan Millman";

  public void setAuthor(String author) { //Error: cannot assign a value to final variable mAuthor
       mAuthor = author;
  }

}
// IN THE DEFAULT CONSTRUCTOR
public class Treet {
  private final String mAuthor;

  Treet(String author) {
     mAuthor = author;
  }

  public void setAuthor(String author) { //Error: cannot assign a value to final variable mAuthor
       mAuthor = author;
  }

}