Search code examples
javakeywordverbosity

Usage patterns for private, static, final, public, abstract keywords in java


I know what all of these do except for abstract. I'm currently in the process of teaching myself java with what I consider a middle-school-level education (my highschool was in a bad neighborhood so I got shafted)...

But what exactly are the usage patterns for these keywords? When do I use what? When do I omit them? Putting 'public' in front of my classes makes every class that uses it require a new file, can I just omit that if I want to create a monolithic source file?

Every bit of information I look up, explains exactly WHAT these do, just doesn't give a clear view of when/why/where I should use them.

Thanks in advance, Anthony


Solution

  • For beginners, here are my rules of thumb:

    1. Public: all classes should be public (this isn't quite true, but it's pretty close). For methods, think about your TV set: stuff you'd expect to do to your TV is "public".
    2. Private: implementation details should be private. Think about your TV set: functionality is private if the equivalent kind of thing for a TV should be private, because the user can mess the TV up permanently, get electrocuted, etc.
    3. Protected: ignore this for now.
    4. Abstract: The best example I read when learning Java was to think about "Bird". Bird is abstact, and therefore would have an "abstract" flight method. Individual species of bird know how to fly (unless they're penguins - then they throw UnsupportedOperationException).

    I would strongly suggest you fight the urge to use one monolithic source file. Try to keep methods shorter than one screenful, and classes shorter than 300 lines.