Java Reference
In-Depth Information
Class and Interface Naming Conventions
Class and interface names should always start with a capital letter, and should be a noun (they
should describe an object, not an action on the object). For example, “Book” might be used as
the name of the class containing information about a topic.
It is common to combine two or more nouns or an adjective and a noun together to form
the class name, in which case CamelCase is used (the first letter of each word is capitalized,
producing the undulating pattern associated with camels). For example, “SocketFactory”
might be used as the name of a class that creates socket connections.
Tip You should try to have only one responsibility for each class. For instance, a class that is responsible
for creating an RMI connection to a server should not also be responsible for displaying data to the end
user. If you can maintain “one responsibility per class,” you will find it easier to name your classes. This
provides a major benefit later when it is time to modify or maintain your classes—the separation of respon-
sibilities and clear class names makes it much easier to determine which classes need to be modified.
Method Naming Conventions
Method names should always start with a lowercase letter, and should begin with a verb (they
should describe an action on the object). For example, within our DVD class, the method
name getLeadActor indicates that we can call this method to get the name of the lead actor
for the DVD.
It is very common to combine several words to give more information on what the
method does. For instance, using the method name getLeadActor makes it far more explicit
when using this method that we are specifically retrieving the lead actor's name (and not the
name of some other person associated with this DVD). As can be seen in this example, Camel-
Case is used when combining words.
Variable Naming Conventions
Variable names should always start with a lowercase letter, should be short, and should
describe what data is stored in the variable. For example, within our DVD class, the variable
name leadActor would contain the names of the lead actor of the film on DVD.
Again, it is very common to combine several words to provide more information on what
the variable does. As you can see in this example, CamelCase is used when combining words.
Note The Sun Coding Conventions specify that you should apply the same naming convention to all
instance, class, and local variables. Be aware that you may see code written by other coders where instance
or class variables are signified by an underscore or some other special mark. Another way to achieve the
same effect is by using the convention variable when referring to a local variable, this.variable when
referring to an instance variable, and Class.variable when referring to a class variable. Doing so makes it
explicit which type of variable you are referring to.
Search WWH ::




Custom Search