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!

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

Aaron Kaye
Aaron Kaye
10,948 Points

Java variables vs getter methods (best practice)

My question came from the Java Data Structures class (Overriding an inherited method) although it is a generic question. I know both of the following would work, but I am wondering which would be 'Best Practice' (assuming the appropriate variables and methods already existed).

    @Override
    public String toString() {
      return "BlogPost: " + getTitle() + " by " + getAuthor();
    }

So the above method uses the objects getter methods to return the instance variables vs:

    @Override
    public String toString() {
      return "BlogPost: " + mTitle + " by " + mAuthor;
    }

As I said, I know both would work with the appropriate variables and methods in place but I am wondering if one is considered 'Best Practice'

1 Answer

Aaron Kaye
Aaron Kaye
10,948 Points

Thanks Kyle, I really appreciate your feedback!