You would use all three in all kinds of programs, except for very simple programs where everything is typically public.
A good practice is to use the most restrictive access modifier that you can. Access modifiers exist to help you stop yourself from making mistakes - they are not actually required per se, but they are very useful. If you're writing a library for other people to use (which you aren't, but you might in the future) they also stop other people doing weird things with your code.
Usually, a class is related to one thing (e.g. a book in a library). If you are writing a library system, you might have a class like this:
public class Book
{
private String title;
public String getTitle() {return title;}
public Book(String t) {title = t;}
...
}
Notice that title
is private, so you can't directly get or set the title of a Book. You can indirectly get it using the getTitle
method, which is public. You can only set it once, when the Book is created.
Code inside the Book class can still set the title, so this is not foolproof. final
would be better for that, but this is to demonstrate access modifiers, not final
.
You could just make title
public, and say that you won't change the title of a book, but later you might do it by mistake. Again, access modifiers help you prevent yourself (and sometimes other people) making mistakes.
Edit: Also, you're wrong about protected
. protected
things are accessible to subclasses or classes in the same package. There's also a default access modifier, which has no keyword, which you get if you don't use public
, protected
or private
. The default access modifier makes things accessible to the same package only.