Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Aaron Kaye
Aaron Kaye
10,936 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,936 Points

Thanks Kyle, I really appreciate your feedback!