Bummer! You must be logged in to access this page.

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 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

I've always been taught to avoid using member variables when possible. Not sure why though. As you said, both work.

Thanks Kyle, I really appreciate your feedback!