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 - Retired Organizing Data Serialization

Why getWordsPrefixedWith(String prefix) is a Private method?

Why Private access modifier was used instead of public ?

Hi Subham,

Where is this at in the video?

Sorry I missed place the question its in the other video named --Using ArrayList--

This is the method added around 3min in the video

  private List<String> getWordsPrefixedWith(String prefix) {
    List<String> results = new ArrayList<String>();
    for (String word : getWords()) {
      if (word.startsWith(prefix)) {
        results.add(word);
      }
    }

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

We make methods private when we don't want for end users of our application, or API to access some methods.

In this case we make getHashTags() and getMentions() public, because in the end these methods will be used in our Application, or in any other class.

The purpose of the getWordsPrefixedWith is ONLY to serve in THIS class, i.e. only here, nothing else, that is why we make it private.

One can make it protected for Unit Testing purposes, but that is whole different story, and we don't want to make it public

 // this one is public, with re-use of helpful method
  public List<String> getHashTags() {
    return getWordsPrefixedWith("#");
  }

// this one is public with re-use of helpful method
  public List<String> getMentions() {
    return getWordsPrefixedWith("@");
  }

  private List<String> getWordsPrefixedWith(String prefix) {
    List<String> results = new ArrayList<String>();
    for (String word : getWords()) {
      if (word.startsWith(prefix)) {
        results.add(word);
      }
    }
    return results;
  }

Rule of thumb is simple: if you write "helpful" method to be used in class only, then you better make it private

Here is the nice video about access-modifiers by Craig

https://teamtreehouse.com/library/access-level-modifiers