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 trialSubham Singh
86 PointsWhy getWordsPrefixedWith(String prefix) is a Private method?
Why Private access modifier was used instead of public ?
Subham Singh
86 PointsSorry 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
Java Web Development Techdegree Graduate 22,175 PointsWe 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
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Subham,
Where is this at in the video?