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

6

12

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

Hidalgo answered 22/2, 2011 at 19:59 Comment(5)
So heres the thing I think you just read an article/book about how to learn java in 10 days. Like abstract isn't a keyword, private and public go together static doesn't do what you say it does. Actually im just confused, I think you need to read a bit more and ask a specific question about specific things.Inaccuracy
@Inaccuracy abstract isn't a keyword? You need to do some soul searching or just some more reading yourself. en.wikipedia.org/wiki/List_of_Java_keywordsMoncear
@Richard yep thats my error, im in c++ world right now, sorry about that mistake. Having said that my point is still validInaccuracy
The official tutorials are a good resource for learning java, the second part of "Trails covering the Basics" should help some download.oracle.com/javase/tutorialAlbuquerque
btw, I don't like the "verbosity" tag. Not that java isn't verbose, but it's not because of these keywords.Piezoelectricity
I
10

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.

Illtreat answered 22/2, 2011 at 20:7 Comment(1)
Yeah, I'm coming from Python, where most files just contain all of the source in a single file. I don't plan on building HUGE projects in java, just using it for small tasks for now and since I don't have the experience, it's really hard to keep track of all the classes when they're split into 100 different files. This question is mainly to help better understand and map out my python knowledge to how java works.Hidalgo
P
42

Sources tell what do these keywords mean because when/why/where they are used follows from that. My explanations have the "when" word, for example, but they follow directly from the semantics of the keywords.

  • private should be used when something is not used outside of a given class
    • for methods and fields - when they are used only within the same class
    • for classes - only on nested classes, when used in the same class
  • protected should be used when
    • for methods and field - when you need to make them accessible to subclasses only
    • for classes - again only nested classes, accessible by subcalsses
  • public is used when something is accessible by every other class

The above three are "visibility modifiers". They are used when you want to limit the usage of some methods/fields/classes to a group of objects, and hide them from other objects. There is another visibility modifier - the default one (when no other is present). It is used when you want your class/method/field to be accessible only to classes from the same package.

  • static is used when you don't need an instance of a class (i.e. object) to use it:
    • for fields - when you want to have a global field
    • for methods - when you need utility functions that do not depend on object state
    • for nested classes - when you want to access them without an instance of the enclosing class.
  • abstract when you don't want to provide implementations in the current class:
    • on methods - when subclasses have to provide the actual implementation, but you want to invoke these methods (no matter how they are implemented) in this class.
    • on classes - to denote that the class may have abstract methods.
  • final - when you don't want something to change.
    • on fields, when you want to assign the value only once. It is useful when you want to pass a local variable to an inner class - you have to declare it final.
    • on classes and methods - when you don't want subclasses to be able to extend / override them.
Piezoelectricity answered 22/2, 2011 at 20:8 Comment(0)
I
10

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.

Illtreat answered 22/2, 2011 at 20:7 Comment(1)
Yeah, I'm coming from Python, where most files just contain all of the source in a single file. I don't plan on building HUGE projects in java, just using it for small tasks for now and since I don't have the experience, it's really hard to keep track of all the classes when they're split into 100 different files. This question is mainly to help better understand and map out my python knowledge to how java works.Hidalgo
C
6

Bozho has covered the uses for the keywords pretty well, but I will add that if you do not declare a scope at all, your scope becomes package-private, which means that anyone in the same package as the class can use that class/method. Basically, it's more permissive than private, but less permissive than just protected, as protected allows access from outside a package.

Information about the 'no modifier' access here:

I recommend going through the Java tutorial:

And also take a look at the book questions if you want to explore more of Java:

Cylix answered 22/2, 2011 at 20:11 Comment(0)
C
2

private, public and protected are all used for declaring the Scope of a class for variable.

static means that the thing being defined is a member of the class and not an object that is instance of the class.

abstract means that the class can not directly created and can only be used by subclasses. An abstract method can be defined in an abstract class and means that any subclass must define a method matching the defined signature.

final means that the variable can only be assigned a variable once at its creation. A final class/method can not be inherited/overridden, respectively.

Stay away from putting everything in one big file. Use an IDE, like Eclipse, and it will make it easy to work with code that has one class per file. It allows you to better organize your code and encapsulate code so you don't end up in a situation where everything knows about everything. This will lead to errors as it becomes easier to accidentally use something the was created to do a different purpose.

Cookhouse answered 22/2, 2011 at 20:7 Comment(0)
A
1

A private method is a method which can’t be accessed by any other object outside the scope it is introduced.

A static method is a method that belongs to a class rather than an instance of a class. The method is accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that member of a class.

The final keyword is used in several contexts to define an entity that can only be assigned once.

The public members are visible to all other classes. This means that any other class can access a public field or method.

The abstract methods don’t have body, they just have method signature.If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well

Aleishaalejandra answered 3/9, 2019 at 14:24 Comment(0)
D
0

In order to understand the when/why/where of these keyword uses, you have to get a grasp on some key concepts of Object Oriented Programming and Java. I suggest looking into Encapsulation and Polymorphism.

Also off the top of my head, I believe 'public' is implied so it isn't required but its good practice to have it there.

Delindadelineate answered 22/2, 2011 at 20:5 Comment(1)
In Java, in most (or perhaps all?) cases, "package" visibility is the defaultObola

© 2022 - 2024 — McMap. All rights reserved.