Defining classes

As we have seen in the examples from previous chapters, a class can simply be defined with Java's class keyword, followed by the class name and brackets { }. The brackets visually show the programmer what code is part of the class:

    class ClassName {
}

The preceding code will compile. It complies with all Java's syntax rules. Removing any part will result in compile errors.

The naming convention for JVM classes is CamelCase. The class name starts with a capital letter. If the class name consists of multiple words, then each word is directly added to the previous one (no spaces or underscores are used) and each word starts with a capital letter. There are several rules for choosing a class name:

  • The name must start with a non-digit character.
  • The name cannot include dashes or spaces. An underscore is valid but not used by convention.
  • Digits are allowed after the first character.
  • Class names may not be keywords reserved for the Java language itself. At least one character must be added or changed so that the name does not violate this rule.